[英]C++ Macro to conditionally compile code?
I want to compile code conditionally based on a macro. 我想基于宏有条件地编译代码。 Basically I have a macro that looks like (Simplified from the real version):
基本上我有一个看起来像的宏(从真实版本简化):
#if DEBUG
#define START_BLOCK( x ) if(DebugVar(#x) \
{ char debugBuf[8192];
#define END_BLOCK( ) printf("%s\n", debugBuf); }
#else
#define START_BLOCK( x ) (void)0;
#define END_BLOCK( ) (void)0;
#endif
The issue is that if DEBUG
is defined you could do things like: 问题在于,如果定义了
DEBUG
,您可以执行以下操作:
START_BLOCK( test )
char str[] = "Test is defined";
strcpy(debugBuf, str);
END_BLOCK( )
START_BLOCK( foo )
char str[] = "Foo is defined";
strcpy(debugBuf, str);
END_BLOCK( )
And everything works fine because each block is within it's own scope. 一切正常,因为每个块都在它自己的范围内。 However if DEBUG isn't defined, then you'd get a redefinition of
str
in the second block. 但是,如果未定义DEBUG,那么您将在第二个块中重新定义
str
。 (Well you'd also get debugBuf
not defined but that's just a side effect of the simplified example.) (嗯,你也得到
debugBuf
没有定义,但这只是简化示例的副作用。)
What I'd like to do is to have the #else be something like: 我想做的是让#else成为:
#else
#define START_BLOCK( x ) #if 0
#define END_BLOCK( ) #endif
#endif
Or some other method of not having anything between the start / end blocks be compiled. 或者编译一些在开始/结束块之间没有任何东西的方法。 I tried the above, I also tried something along the lines of:
我尝试了以上内容,我也尝试过以下方面:
#else
#define NULLMACRO( ... ) (void)0
#define START_BLOCK( x ) NULLMACRO(
#define END_BLOCK( ) )
#endif
without any luck. 没有运气。
Is there a way for this to work? 这有什么办法吗? One thought that just occurred to me is that I could maybe abuse the optimizing compiler and use:
我刚想到的一个想法是,我可能会滥用优化编译器并使用:
#else
#define START_BLOCK( x ) if(0){
#define END_BLOCK( ) }
#endif
And trust that it will just compile out the block completely. 并相信它会完全编译出来。 Are there any other solutions?
还有其他解决方案吗?
So you want conditional blocks with their own scope? 那么你想要条件块有自己的范围?
Here's a quite readable solution that relies on the compiler to optimize it away: 这是一个非常易读的解决方案,它依赖于编译器来优化它:
#define DEBUG 1
if (DEBUG) {
// ...
}
And here is one that is preprocessor-only: 这是一个仅预处理器:
#define DEBUG 1
#ifdef DEBUG
#define IFDEBUG(x) {x}
#else
#define IFDEBUG(x)
#endif
IFDEBUG(
// ...
)
Or manually: 或手动:
#define DEBUG 1
#ifdef DEBUG
{
// ...
}
#endif
Would: 将:
#if DEBUG
#define START_BLOCK( x ) if(DebugVar(#x) \
{ char debugBuf[8192];
#define END_BLOCK( ) printf("%s\n", debugBuf); }
#else
#define START_BLOCK( x ) {
#define END_BLOCK( ) }
#endif
do? 做?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.