Home > OS >  C macro to interpolate argument in function call
C macro to interpolate argument in function call

Time:10-27

I want to create a macro that adds a prefix to the argument and calls it as a function. Something like this:

#define FUNC(name) /* some code */

FUNC(add)      // => __some_function_name_prefix__add()
FUNC(subtract) // => __some_function_name_prefix__subtract()
FUNC(multiply) // => __some_function_name_prefix__multiply()
FUNC(divide)   // => __some_function_name_prefix__divide()

This is what I have tried:

#define FUNC(name) __some_function_name_prefix__name()

FUNC(add)      // => __some_function_name_prefix__name()
FUNC(subtract) // => __some_function_name_prefix__name()
FUNC(multiply) // => __some_function_name_prefix__name()
FUNC(divide)   // => __some_function_name_prefix__name()

But, he problem is that it will always expand to __some_function_name_prefix__name() and won't use the argument. How can I fix this?

CodePudding user response:

#define FUNC(name) __some_function_name_prefix__##name()

CodePudding user response:

Use the token pasting operator ## in the macro. See https://learn.microsoft.com/en-us/cpp/preprocessor/token-pasting-operator-hash-hash.

  • Related