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?

标签: c macros
1条回答
倾城 Initia
2楼-- · 2019-01-09 12:32

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
查看更多
登录 后发表回答