我想根据宏有条件地编译代码。基本上我有一个看起来像这样的宏(从真实版本简化):
#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
并相信它会完全编译出该块。还有其他解决方案吗?