【问题标题】:C++ Macro to conditionally compile code?C ++宏有条件地编译代码?
【发布时间】: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

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

【问题讨论】:

    标签: c++ macros


    【解决方案1】:

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

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

    #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
    

    【讨论】:

    • 我原来有你的中间那个,问题是 gcc 与 Visual Studio 如何处理 0 或 1 arg 的 var args,我的简化示例没有涵盖,该死。
    • @Doug-W:谁在谈论可变参数?
    • 好吧,如果你的表达式包含任何逗号,那么你的中间那个就不起作用。很长的代码块包含逗号是很常见的。一种解决方法是可变参数(它将包括所有内容、逗号和所有内容),但可变参数不能很好地处理低参数计数的情况。
    【解决方案2】:

    会:

    #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
    

    做吗?

    【讨论】:

      猜你喜欢
      • 2013-08-26
      • 2020-02-06
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      相关资源
      最近更新 更多