C ++宏有条件地编译代码?

时间:2011-09-10 14:41:28

标签: c++ macros

我想基于宏有条件地编译代码。基本上我有一个看起来像的宏(从真实版本简化):

#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

并相信它会完全编译出来。还有其他解决方案吗?

2 个答案:

答案 0 :(得分:5)

所以你想要条件块有自己的范围吗?

这是一个非常易读的解决方案,依赖于编译器来优化它:

#define DEBUG 1

if (DEBUG) {
    // ...
}

这是一个仅预处理器:

#define DEBUG 1

#ifdef DEBUG
    #define IFDEBUG(x) {x}
#else
    #define IFDEBUG(x)
#endif

IFDEBUG(
    // ...
)

或手动:

#define DEBUG 1

#ifdef DEBUG
{
    // ...
}
#endif

答案 1 :(得分:1)

将:

#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

办?