我希望你能根据宏条件编译代码。基本上,我有一个宏看起来像这样(从真实版本简化):
问题在于如果定义了
#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
问题在于如果定义了
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( )
每个块都在其自己的作用域内,所以一切正常。然而,如果未定义DEBUG,那么您将在第二个块中重新定义str
。(好吧,您还会得到debugBuf
未定义,但这只是简化示例的副作用。)
我想做的是让# else成为以下内容:
#else
#define START_BLOCK( x ) #if 0
#define END_BLOCK( ) #endif
#endif
或者其他不需要在开始/结束块之间编译任何内容的方法。我尝试了上面的方法,也尝试了类似以下的方法:
#else
#define NULLMACRO( ... ) (void)0
#define START_BLOCK( x ) NULLMACRO(
#define END_BLOCK( ) )
#endif
没有任何运气。
有没有办法让它工作?我刚想到的一个想法是,我可以滥用优化编译器并使用:
#else
#define START_BLOCK( x ) if(0){
#define END_BLOCK( ) }
#endif
并且相信它将完全编译出该块。是否还有其他解决方案?