How to concatenate strings with C preprocessor with dots in them?

烂漫一生 提交于 2019-12-10 13:51:19

问题


I've read the following question and the answer seems clear enough: How to concatenate twice with the C preprocessor and expand a macro as in "arg ## _ ## MACRO"?

But what if VARIABLE has a dot at the end?

I'm trying to do a simple macro that increments counters in a struct for debugging purposes. I can easily do this even without the help from the above question simply with

#ifdef DEBUG
#define DEBUG_INC_COUNTER(x) x++
#endif

and call it

DEBUG_INC_COUNT(debugObj.var1);

But adding "debugObj." to every macro seems awfully redundant. However if I try to concatenate:

#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

I get

macro.c:6:1: error: pasting "." and "var" does not give a valid preprocessing token

So how should I change this so that

DEBUG_INC_COUNTER(var);

generates

debugObj.var++;

?


回答1:


Omit the ##; this is only necessary if you want to join strings. Since the arguments aren't strings, the spaces between them don't matter (debugObj . var1 is the same as debugObj.var1).




回答2:


You should not paste them together using ##, as you can have debugObj ., and var1 as separate preprocessor tokens.

The following should work:

#define DEBUG_INC_COUNTER(x) debugObj.x++


来源:https://stackoverflow.com/questions/10085594/how-to-concatenate-strings-with-c-preprocessor-with-dots-in-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!