不是所有的token在宏定义中都可以使用##连接

6 篇文章 0 订阅
4 篇文章 0 订阅

我定义了下面几个宏:

#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编译就不会报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值