Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

?

like image 692
Makis Avatar asked Apr 10 '12 08:04

Makis


People also ask

Can you concatenate C style strings?

Example 1: Concatenate String ObjectsYou can concatenate two C-style strings in C++ using strcat() function.

What is ## in preprocessor?

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.

Which symbols is used to concatenate strings?

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.


2 Answers

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

like image 83
Aaron Digulla Avatar answered Oct 04 '22 12:10

Aaron Digulla


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++
like image 25
Lindydancer Avatar answered Oct 04 '22 13:10

Lindydancer