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++;
?
Example 1: Concatenate String ObjectsYou can concatenate two C-style strings in C++ using strcat() function.
The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.
The ampersand symbol is the recommended concatenation operator. It is used to bind a number of string variables together, creating one string from two or more individual strings.
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
).
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++
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With