【问题标题】:How to concatenate macros in CPP如何在 CPP 中连接宏
【发布时间】:2018-07-07 17:31:40
【问题描述】:
#define STR1 "NEW"
#define STR2 PILLAR
#define MAKE_STR(x) #x
#define STR3 STR1 MAKE_STR(STR2)
printf(STR3 " hello world\n");

上面的语句扩展为

printf("NEWSTR2 hello world\n");

我需要像“NEWPILLAR hello world”这样的东西。有输入吗?

【问题讨论】:

  • 其实宏扩展为printf("NEW" "STR2" " hello world\n");。使用编译器(或等效项)的 -E 标志仅调用预处理器;不要假设 printf 打印的是预处理器所做的。

标签: c macros concatenation c-preprocessor


【解决方案1】:

在字符串化之前扩展STR2

#define STR1 "NEW"
// #define STR2 PILLAR
#define STR2 MAKE_STR(PILLAR)
#define MAKE_STR(x) #x
// #define STR3 STR1 MAKE_STR(STR2)
#define STR3 STR1 STR2
printf(STR3 " hello world\n");

或者,如果您确实需要从其他地方定义STR2

#define EXPAND_MAKE_STR(x) MAKE_STR(x)
#define STR3 STR1 EXPAND_MAKE_STR(STR2)

【讨论】:

  • 做了完全相同的事情,但我仍然看到同样的问题。
  • 我认为问题似乎出在 STR2 上。您的代码完全按照预期工作。定义 STR2 是从生成文件传递的,所以如果我用 #define STR2 PILLAR #define MK_STR2 MAKE_STR(STR2) 替换此语句,我会将打印读取为 => NEWSTR2 hello world
  • @CPPGuy 我在答案中测试了代码,它给出了预期的结果。
  • #define STR1 "NEW" #define STR2 PILLAR #define MAKE_STR(x) #x #define MK_STR2 MAKE_STR(STR2) #define STR3 STR1 MK_STR2 printf(STR3 "hello world\n");你可以试试这个吗?
  • @CPPGuy:从 makefile 中定义宏增加了额外的复杂性——shell 阻碍了双引号、单引号和不带引号的哈希 (#)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-11
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 2011-12-25
  • 1970-01-01
  • 2019-11-06
相关资源
最近更新 更多