【问题标题】:C++ Combining #define and #ifndef macroC++ 结合#define 和#ifndef 宏
【发布时间】:2014-07-15 14:53:15
【问题描述】:

我想知道是否有一种方法可以将#define 和#ifndef 宏结合起来..

这意味着我想在#define 宏中使用#ifndef 宏..

由于有点难以解释,这是我想做的一个例子:

#define RUN_IF_DEBUG                \
    #ifndef DEBUG_MODE              \
        ;      // do nothing        \
    #else                           \
        cout << "Run!" << endl;     \
    #endif

int main() {
    RUN_IF_DEBUG
}

所以我希望 RUN_IF_DEBUG 宏仅在定义了 DEBUG_MODE 时运行...

有没有办法做到这一点?

【问题讨论】:

  • 您可以在行尾不带“\”的情况下进行嵌套定义
  • @cerkiewny,你不能做嵌套定义期间(至少没有黑客),因为你不能在宏中使用其他指令保存 _Pragma

标签: c++ macros


【解决方案1】:

通常情况相反:

#ifndef DEBUG_MODE
#  define RUN_IF_DEBUG ;
#else
#  define RUN_IF_DEBUG cout << "Run!" << endl;
#endif

【讨论】:

    【解决方案2】:

    简单的做

    #ifndef DEBUG_MODE
        #define RUN_IF_DEBUG ;      // do nothing
    #else
        #define RUN_IF_DEBUG cout << "Run!" << endl;
    #endif
    

    您不能将其他预处理器语句放在宏的主体中。

    来自c++ standards definitions草稿部分

    16 个预处理指令

    ...
    控制线:
    ...
    # define identifier 替换列表换行
    # define identifier lparen identifier-listopt) 替换列表换行
    # define identifier lparen ... ) replacement-list new-line
    # define identifier lparen identifier-list, ... ) replacement-list new -线

    这些是#define 语句允许的语法变体。

    `

    【讨论】:

      【解决方案3】:

      问题是宏中的续行。他们所做的是将所有内容放在一行中,因此扩展的宏看起来像

      int main() {
          #ifndef DEBUG_MODE ; #else cout ...; #endif
      }
      

      这不适用于预处理器或编译器。

      相反,您应该切换嵌套,并首先使用#ifndef,然后在内部级别使用#define 宏。

      【讨论】:

        猜你喜欢
        • 2014-12-08
        • 1970-01-01
        • 1970-01-01
        • 2020-09-26
        • 2010-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多