这是我所想的。
#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("%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)) ===|
arg ## _ ## MACRO
”?以详细讨论标记连接的工作原理。您不能像问题中所示那样在宏名称中使用##
;它必须在类似函数的宏的扩展中使用。 - Jonathan Leffler#define macroA(x) I_am_macro_ ## x
和#define macroB(x) "I_am_macro_" #x
有什么区别?macroA(2)
展开为I_am_macro_2
。 - marom