不是所有的token在宏定义中都可以使用##连接
作者:互联网
我定义了下面几个宏:
#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编译就不会报错。
标签:定义,##,STR,token,zz,home,IMPL,CONNAT 来源: https://blog.csdn.net/wangw8507/article/details/122472798