c++ - 是否可以从宏定义宏

标签 c++ c macros

这是我的想法。

#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)) ===|

因此,如果您希望能够拥有宏,您只需正常添加前缀即可。幸运的是,您基本上已经这样做了,只是添加了“##”。希望这对您有所帮助。

关于c++ - 是否可以从宏定义宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31801705/

相关文章:

如果没有 LNK2005 错误,则无法包含 C++ header

c++ - regex_search 抛出 std::regex_error

c++ - 在 C++ 中直接访问文件?

c++ - 结合 CMake option() 与 add_definitions()

c++ - 链接到 boost 库

c++ - 仅使用 LogonUser() 来验证凭据

c - 如何使#if#endif 成为宏的一部分

Objective-C 安全转换宏

c - 结构体中 char 数组的初始化

c - 如何从非文本文件中读取、修改结构?