是否可以从宏中定义宏

Is it possible to define a macro from a macro

本文关键字:定义 是否      更新时间:2023-10-16

我是这么想的

#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

这可能吗?

不幸的是,你想做的是不可能的。(##)指令不能在宏声明中使用。它只能在定义中使用。

#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("%sn%sn%sn", 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)) ===|

所以如果你想要能够有宏,你只需要添加前缀通常。幸运的是,你基本上已经这样做了,只是添加了"##"。