C: Expand Macro With Token Pasting

2019-01-09 11:58发布

问题:

So here are some macros I have created:

#define MODULE_NAME moduleName
#define MODULE_STRUCT MODULE_NAME ## _struct
#define MODULE_FUNCTION(name) MODULE_NAME ## _ ## name

After those definitions, I would like the following expansions to happen:

MODULE_STRUCT   -->   moduleName_struct
MODULE_FUNCTION(functionName)    -->    moduleName_functionName

However, when I add the token pasting operators, expansion of MODULE_NAME within MODULE_FUNCTION and MODULE_STRUCT no longer happens... It seems to consider MODULE_NAME as a literal string when pasting them together.

Is there a way around this?

回答1:

In C the operands of the token pasting operator ## are not expanded.

You need a second level of indirection to get the expansion.

#define CAT(x, y) CAT_(x, y)
#define CAT_(x, y) x ## y


标签: c macros