我定义了下面几个宏:
#define CONNAT(a, b) CONNAT_IMPL(a, b)
#define CONNAT_IMPL(a, b) a##b
#define STR(s) STR_IMPL(s)
#define STR_IMPL(s) #s
然后再代码中使用:
std::string str = STR(CONNAT(/home/boy/, zz));
我的本意是想得到一个字符串"/home/boy/zz"
但是GCC编译器给出了编译错误:
error: pasting "/" and "zz" does not give a valid preprocessing token
如果将 std::string str = STR(CONNAT(/home/boy/, zz)); 改成std::string str = STR(CONNAT(/home/boy_, zz)); 就没有问题。
看了一下GCC对宏连接处理的说明,发现有些符号是不能用于宏连接的,譬如上面的'/'。
Keep in mind that the C preprocessor converts comments to whitespace before macros are even considered. Therefore, you cannot create a comment by concatenating `/' and `*'. You can put as much whitespace between `##' and its operands as you like, including comments, and you can put comments in arguments that will be concatenated. However, it is an error if `##' appears at either end of a macro body.
GCC文档链接:Concatenation - The C Preprocessor
注意:这种问题和编译器有关系,使用MSVC编译就不会报错。

本文探讨了在C/C++中使用预处理器宏进行字符串拼接时遇到的问题,并通过具体例子展示了特定字符如'/'在宏连接中的限制。同时指出该问题与编译器相关,例如GCC与MSVC的表现不同。
3万+

被折叠的 条评论
为什么被折叠?



