Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C macro to interpolate argument in function call

I want to create a macro that adds a prefix to the argument, then uses the result as the name of a function. I want it to work 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, it will always expand to __some_function_name_prefix__name() and won’t use the argument. How can I fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading