【发布时间】:2011-09-10 14:41:28
【问题描述】:
我想根据宏有条件地编译代码。基本上我有一个看起来像的宏(从真实版本简化):
#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
并相信它会完全编译出块。还有其他解决方案吗?
【问题讨论】: