能否从一个宏定义另一个宏?

5

这是我所想的。

#define prefix_1 1
#define prefix_2 2
#define prefix_3 3

我希望使用上述前缀来定义宏,例如宏macro_prefix_1 macro_prefix_2,我期望它们会变成macro_1 macro_2等。就像下面的代码一样。
#define macro_##prefix_1 I_am_macro_1
#define macro_##prefix_2 I_am_macro_2

这是否可能?


3
简洁明了地说,不行。至少不是那样子。 - Jonathan Leffler
你试过了吗?在gcc中,使用-E选项可以获得预处理阶段的结果。 - John3136
1
请参阅如何使用C预处理器两次连接并扩展宏,例如“arg ## _ ## MACRO”?以详细讨论标记连接的工作原理。您不能像问题中所示那样在宏名称中使用##;它必须在类似函数的宏的扩展中使用。 - Jonathan Leffler
1
#define macroA(x) I_am_macro_ ## x#define macroB(x) "I_am_macro_" #x 有什么区别?macroA(2) 展开为 I_am_macro_2 - marom
@JonathanLeffler 谢谢,那很有帮助。 - richard.g
1个回答

2
很遗憾,您想要做的事情是不可能的。 (##) 指令无法在宏声明中使用。只能在定义中使用。请注意保留 HTML 标签。
#define glue(a,b) a ## b
glue(c,out) << "test";

本例子来自cplusplus.com

下面是一个示例,展示了您想要实现的内容。

#include <stdio.h>

#define prefix_1 1
#define prefix_2 2
#define prefix_3 3

#define macro_##prefix_1 "macro_1"
#define macro_##prefix_2 "macro_2"
#define macro_##prefix_3 "macro_3"

int main(){
    printf("%s\n%s\n%s\n", macro_prefix_1, macro_prefix_2, macro_prefix_3);
    return 0;
}

当您尝试编译以上代码时,将会得到以下构建日志。
||=== Build: Debug in file_test (compiler: GNU GCC Compiler) ===|
main.cpp|7|warning: missing whitespace after the macro name [enabled by default]|
main.cpp|7|error: '##' cannot appear at either end of a macro expansion|
main.cpp|8|warning: missing whitespace after the macro name [enabled by default]|
main.cpp|8|error: '##' cannot appear at either end of a macro expansion|
main.cpp|9|warning: missing whitespace after the macro name [enabled by default]|
main.cpp|9|error: '##' cannot appear at either end of a macro expansion|

main.cpp||In function 'int main()':|
main.cpp|13|error: 'macro_prefix_1' was not declared in this scope|
main.cpp|13|error: 'macro_prefix_2' was not declared in this scope|
main.cpp|13|error: 'macro_prefix_3' was not declared in this scope|
||=== Build failed: 6 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|

如果您想使用宏,只需要添加通常的前缀即可。幸运的是,您已经基本上做到了这一点,只需要添加“##”。希望这有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接