对于字符串文字,您不需要这种解决方案,因为它们是在语言级别连接的,而且无论如何它都不会工作,因为“s”“1”不是有效的预处理器标记。
[编辑:为了回应下面错误的“仅供记录”评论,不幸收到了几个赞成票,我将重申上面的声明并观察程序片段
#define PPCAT_NX(A, B) A ## B
PPCAT_NX("s", "1")
从 gcc 的预处理阶段产生此错误消息:错误:粘贴“s”和“1”不提供有效的预处理令牌
]
但是,对于一般的令牌粘贴,试试这个:
/*
* 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) 生成 <macro value of s>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)"