c语言宏两个字符串连接,C / C ++宏字符串连接

你不需要那种字符串文字的解决方案,因为它们在语言级别连接,并且它无论如何都不会起作用,因为“s”“1”不是有效的预处理器标记。

[编辑:为了回应下面不正确的“仅供记录”评论,不幸收到了几个赞成票,我将重申上述声明并观察程序片段

#define PPCAT_NX(A, B) A ## B

PPCAT_NX("s1", "s2")

从gcc的预处理阶段产生此错误消息:error:pasting“”s1“”和“”s2“”不提供有效的预处理令牌

]

但是,对于一般的令牌粘贴,请尝试以下方法:

/*

* Concatenate preprocessor tokens A and B without expanding macro definitions

* (however, if invoked from a macro, macro arguments are expanded).

*/

#define PPCAT_NX(A, B) A ## B

/*

* Concatenate preprocessor tokens A and B after macro-expanding them.

*/

#define PPCAT(A, B) PPCAT_NX(A, B)

然后,例如,两者PPCAT_NX(s, 1)并PPCAT(s, 1)产生标识符s1,除非s被定义为宏,在这种情况下PPCAT(s, 1)产生1。

继续主题是这些宏:

/*

* Turn A into a string literal without expanding macro definitions

* (however, if invoked from a macro, macro arguments are expanded).

*/

#define STRINGIZE_NX(A) #A

/*

* Turn A into a string literal after macro-expanding it.

*/

#define STRINGIZE(A) STRINGIZE_NX(A)

然后,

#define T1 s

#define T2 1

STRINGIZE(PPCAT(T1, T2)) // produces "s1"

相比之下,

STRINGIZE(PPCAT_NX(T1, T2)) // produces "T1T2"

STRINGIZE_NX(PPCAT_NX(T1, T2)) // produces "PPCAT_NX(T1, T2)"

#define T1T2 visit the zoo

STRINGIZE(PPCAT_NX(T1, T2)) // produces "visit the zoo"

STRINGIZE_NX(PPCAT(T1, T2)) // produces "PPCAT(T1, T2)"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值