Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Expand Macro With Token Pasting

Tags:

c

macros

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?

like image 675
BraedenP Avatar asked Sep 27 '12 21:09

BraedenP


People also ask

What does ## do in a macro?

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.

How are macros expanded in C?

The LENGTH and BREADTH are called the macro templates. The values 10 and 20 are called macro expansions. When the program run and if the C preprocessor sees an instance of a macro within the program code, it will do the macro expansion. It replaces the macro template with the value of macro expansion.

What is ## in preprocessor?

This is called token pasting or token concatenation. The ' ## ' preprocessing operator performs token pasting. When a macro is expanded, the two tokens on either side of each ' ## ' operator are combined into a single token, which then replaces the ' ## ' and the two original tokens in the macro expansion.

What is __va_args __?

Here also we have to include ellipsis, The '__VA_ARGS__' is used to handle variable length arguments. Concatenation operator '##' is used to concatenate the variable arguments. In this example, the Macro will take variable length argument like the printf() or scanf() function.


1 Answers

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
like image 81
ouah Avatar answered Sep 24 '22 17:09

ouah