如何使用带有点的C预处理器连接字符串?

Mak*_*kis 5 c concatenation c-preprocessor

我已经阅读了以下问题,答案似乎很清楚: 如何使用C预处理器连接两次并扩展宏,如"arg ## _ ## MACRO"?

但是如果VARIABLE最后有一个点呢?

我正在尝试做一个简单的宏,增加结构中的计数器以进行调试.即使没有上述问题的帮助,我也可以轻松地做到这一点

#ifdef DEBUG
#define DEBUG_INC_COUNTER(x) x++
#endif
Run Code Online (Sandbox Code Playgroud)

并称之为

DEBUG_INC_COUNT(debugObj.var1);
Run Code Online (Sandbox Code Playgroud)

但是添加"debugObj".每个宏看起来都非常多余.但是,如果我尝试连接:

#define VARIABLE debugObj.
#define PASTER(x,y) x ## y++
#define EVALUATOR(x,y)  PASTER(x,y)
#define DEBUG_INC_COUNTER(x) EVALUATOR(VARIABLE, x)
DEBUG_INC_COUNTER(var)

gcc -E macro.c
Run Code Online (Sandbox Code Playgroud)

我明白了

macro.c:6:1: error: pasting "." and "var" does not give a valid preprocessing token
Run Code Online (Sandbox Code Playgroud)

那么我应该如何改变这一点呢

DEBUG_INC_COUNTER(var);
Run Code Online (Sandbox Code Playgroud)

生成

debugObj.var++;
Run Code Online (Sandbox Code Playgroud)

Lin*_*cer 6

您不应该使用##debugObj .、 和var1作为单独的预处理器标记将它们粘贴在一起。

以下应该工作:

#define DEBUG_INC_COUNTER(x) debugObj.x++
Run Code Online (Sandbox Code Playgroud)


Aar*_*lla 5

省略##; 只有在想要连接字符串时才需要这样做.由于参数不是字符串,因此它们之间的空格无关紧要(debugObj . var1与之相同debugObj.var1).