【问题标题】:Pre-processor: Expand a macro only once预处理器:宏只展开一次
【发布时间】:2022-01-01 09:59:04
【问题描述】:

是否可以只扩展一次宏?在以下示例中,MYCONCAT 扩展为 func_1(10)。我希望它扩展到func_BAR(10)

#define BAR 1  // included from a file I cannot change
#define FOO BAR

#define MYCONCAT2(c) func_ ## c
#define MYCONCAT(c, x) MYCONCAT2(c)(x)

MYCONCAT(FOO, 10) // is 'func_1(10)', but I want it to be 'func_BAR(10)'

【问题讨论】:

  • 你可以#undef BAR
  • 并不是说宏只展开一次;示例中的每个宏仅扩展一次:MYCONCAT 到带有 MYCONCAT2 的文本,MYCONCAT2func_ ## cFOOBAR,以及 BAR1。您想要的是宏替换过程本身受到限制。
  • 我觉得我们需要更多的上下文。如果您不希望 BAR 以这种方式扩展,为什么将其定义为 1?这个奇怪装置的最终目标和用例是什么?
  • 你可以用枚举来代替#define常量。
  • 您能否将定义BAR 的文件包含在您使用MYCONCAT 的点之后而不是之前?

标签: c c-preprocessor preprocessor


【解决方案1】:

宏是否可以只展开一次?

不,不能部分扩展宏。

【讨论】:

    【解决方案2】:

    仅在使用MYCONCAT 的最后一个位置(扩展为BAR)而不是之前包含定义BAR 的文件。

    【讨论】:

      【解决方案3】:

      只需将#define BAR 更改为#define _BAR 并从func 中删除_

      #define BAR 1  // included from a file I cannot change
      #define FOO _BAR
      
      #define MYCONCAT2(c) func ## c
      #define MYCONCAT(c, x) MYCONCAT2(c)(x)
      
      MYCONCAT(FOO, 10) // 'func_BAR(10)'
      

      【讨论】:

        猜你喜欢
        • 2012-09-20
        • 1970-01-01
        • 2018-01-04
        • 1970-01-01
        • 2020-10-18
        • 1970-01-01
        • 1970-01-01
        • 2010-12-02
        相关资源
        最近更新 更多