7
votes

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++;

?

2

2 Answers

9
votes

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).

6
votes

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++