【问题标题】:Composition of token-glueing macros标记粘合宏的组成
【发布时间】:2014-03-12 14:55:22
【问题描述】:

我得到了这些宏

#define NEXT(of_) ((of_ ## _SUFFIX) + 1)
#define AA_SUFFIX (1)
#define BB_SUFFIX (NEXT(AA))  // expands to ((((1)) + 1))
#define CC_SUFFIX (NEXT(BB))  // expands to ((((NEXT(AA))) + 1)) !!!

我希望 CC_SUFFIX 扩展为 3,但它没有(见上文)。 在这种情况下,有没有办法让预处理器评估 NEXT(AA) ?

【问题讨论】:

    标签: c c-preprocessor


    【解决方案1】:

    根据this 的回答,预处理器“[...] 递归地扩展替换文本以替换出现的其他宏(宏本身在这些递归调用中被阻止。)”

    考虑到这一点,CC_SUFFIX 的扩展最终成为 ((((NEXT(AA))) + 1)) 是有道理的,因为宏 NEXT(of_) 已经使用过一次。要确认这是原因,您可以创建一个与NEXT(of_) 执行相同操作的新宏并在BB_SUFFIX 中使用它:

    #define NEXT(of_) ((of_ ## _SUFFIX) + 1)
    #define NEXT1(of_) ((of_ ## _SUFFIX) + 1)
    #define AA_SUFFIX (1)
    #define BB_SUFFIX (NEXT1(AA))
    #define CC_SUFFIX (NEXT(BB))
    
    int main(void){
      BB_SUFFIX;
      CC_SUFFIX;
    }
    

    运行gcc -E macros.c输出为:

    # 1 "/home/jfacorro/dev/macros-expand.c"
    # 1 "<command-line>"
    # 1 "/home/jfacorro/dev/macros-expand.c"
    int main(void){
      ((((1)) + 1));
      (((((((1)) + 1))) + 1));
    }
    

    作为旁注,没有必要将宏的表达式括在括号中,如果丢失它们,扩展会读起来更清晰。

    #define NEXT(of_) of_ ## _SUFFIX + 1
    #define NEXT1(of_) of_ ## _SUFFIX + 1
    #define AA_SUFFIX 1
    #define BB_SUFFIX NEXT1(AA)
    #define CC_SUFFIX NEXT(BB)
    

    产生输出:

    int main(void){
      1 + 1;
      1 + 1 + 1;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2011-03-24
      • 1970-01-01
      • 2019-12-05
      • 2013-07-14
      • 2012-11-06
      相关资源
      最近更新 更多