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

独自空忆成欢 提交于 2019-12-11 05:05:30

问题


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)


来源:https://stackoverflow.com/questions/17595470/how-to-pass-a-macros-result-to-another-macro

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