你不需要那种字符串文字的解决方案,因为它们在语言级别连接,并且它无论如何都不会起作用,因为“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)"