C++有条件编译代码的宏?
我想根据宏有条件地编译代码。基本上我有一个看起来像(从真实版本简化)的宏:
#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
not Defined ,但这只是简化示例的副作用。)
我想做的是让 #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
并相信它会完全编译出该块。还有其他解决方案吗?
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:
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. (Well you'd also get debugBuf
not defined but that's just a side effect of the simplified example.)
What I'd like to do is to have the #else be something like:
#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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那么您想要具有自己范围的条件块吗?
这是一个非常可读的解决方案,它依赖于编译器来优化它:
这是一个仅预处理器的解决方案:
或者手动:
So you want conditional blocks with their own scope?
Here's a quite readable solution that relies on the compiler to optimize it away:
And here is one that is preprocessor-only:
Or manually:
会:
会吗?
Would:
do?