预处理器出现问题 - 连接 "name" 和“=”作为标记时

trouble with the preprocessor - when concatenating "name" and "=" as tokens

代码如下:

#define STR_CONCAT_IMPL(s1, s2) s1##s2
#define STR_CONCAT(s1, s2) STR_CONCAT_IMPL(s1, s2)
#define TOSTR_IMPL(x) #x
#define TOSTR(x) TOSTR_IMPL(x)
#define STR_CONCAT_TOSTR(s1, s2) TOSTR(STR_CONCAT(s1, s2))

int main() {
    const char* a = STR_CONCAT_TOSTR(name, p); // works
    const char* b = STR_CONCAT_TOSTR(name, =); // doesn't work
    return 0;
}

我在编译时需要来自 "name""name=" 之类的字符串(运行时连接不是一个选项)所以我尝试使用我的旧宏但是我得到了这个错误:

error: pasting "name" and "=" does not give a valid preprocessing token

但当不使用 = 而使用普通字符时 - 它有效。

我怎样才能让它工作?

C++98 GCC/MSVC 需要解决方案。

我假设您为此需要一个宏,不能只使用编译器本身。

利用连接的相邻字符串文字:

#define STR_CONCAT_TOSTR(s1, s2) TOSTR(s1) TOSTR(s2)

在这种情况下,STR_CONCAT_TOSTR(name, =) 扩展为 "name" "=",编译器将其转换为 "name="

那是因为 name= 不是一个标记,它是两个。因此,与 namep 不同,它们不能被粘贴以生成单个标记。

您需要做的就是以不同的方式定义 STR_CONCAT_TOSTR 以连接起始标记的字符串文字,而不是首先尝试连接标记:

#define STR_CONCAT_TOSTR(s1, s2) (TOSTR(s1) TOSTR(s2))