How to pass a macro's result to another macro?

2019-08-06 04:57发布

问题:

I have two macros in my C code the helps me to compose the name of certain variables. As an example, consider the following:

#define MACROA(name) A_##name
#define MACROB(name) B_##name

void *MACROB(MACROA(object));

So, I'm trying to declare a variable called B_A_object. However, this doesn't work and the compiler throws me the message:

object.c:27:21: error: a parameter list without types is only allowed in a function definition
void *MACROB(MACROA(object));
                    ^
object.c:26:26: note: expanded from macro 'MACROB'
#define MACROB(name) B_##name
                         ^

So, it seems the preprocessor is not taking the result of MACROA(object), but it is considering the expression itself so that it tries to make B_MACROA(object). So, what do I have to do to make the preprocessor consider the result of a macro passed to another macro?

回答1:

The concatenation operator acts weird. It concatenates first and evaluates later:

void *MACROB(MACROA(object));  // The original line
void *B_MACROA(object);       // Becomes this, nothing more to expand

You can solve it this way:

#define CONC(a,b) a ## b
#define MACROA(name) CONC(A_, name)
#define MACROB(name) CONC(B_, name)