如何在 C 中连接两个字符串宏?

Xto*_*dam 2 c macros preprocessor concatenation

我正在尝试为我的程序实现 VERSION 宏,该宏将在某些情况下进行更改。

宏 VERSION 通过 Makefile 定义(git 信息放在那里)并且是一个字符串。现在我有一组#define'd 开关,我希望 VERSION 能够反映其中哪些开关处于打开状态。现在看起来如下(main.h):

#define COMPLEX_DEPOSITION // This is switch. later in code it is used in #ifdef...#endif construction.

#ifdef COMPLEX_DEPOSITION
#define CD "_COMP_DEP" // this is the string I want to put in the end of VERSION
#define VERSION_ VERSION CD

#undef VERSION // this is to suppress 'macro redefinition' warning
#define VERSION VERSION_
#undef VERSION_
#endif
Run Code Online (Sandbox Code Playgroud)

嗯,我遇到了很多错误,其中大部分让我认为 C 预处理器以随机顺序处理文件中的行:(

后来我有一个更复杂的事情,旨在使VERSION -> VERSION_WLT_GAP_2

#define COMPLEX_DEPOSITION // This is switch. later in code it is used in #ifdef...#endif construction.

#ifdef COMPLEX_DEPOSITION
#define CD "_COMP_DEP" // this is the string I want to put in the end of VERSION
#define VERSION_ VERSION CD

#undef VERSION // this is to suppress 'macro redefinition' warning
#define VERSION VERSION_
#undef VERSION_
#endif
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么做,也不知道这是否可能

PSk*_*cik 6

字符串文字彼此相邻放置时会自然连接

"foo" "bar"是相同的"foobar"

至于第二个例子,您可能想要:

#define CAT_(A,B) A##B
#define CAT(A,B) CAT_(A,B)

#define GAP 2
#define VERSION CAT(VERSION_WLT_GAP_ , GAP)

VERSION //expands to VERSION_WLT_GAP_2
Run Code Online (Sandbox Code Playgroud)

我建议在尝试用gcc -E/clang -E编写任何复杂的内容之前,先使用 / 来了解宏的工作原理。