2
votes

I'm trying to figure out how to write a C Preprocessor macro that can accept a partial function name and a piece of text to append to the function name along with a set of arguments to create the actual function name and function call. The idea is to combine the first two macro arguments to create a function name and then add the rest of the macro arguments as arguments for the function name created.

So I want to achieve the following:

MACRO(foo, postfix, ...)
----> foo_postfix(__VA_ARGS__)

For instance if I have several C functions, func_test1() and func_test2() and func_test3() then I want to be able to use the macro to specify func as the first argument and test1 as the second argument so that the macro will create a function name of func_test1(), or to specify func as the first argument and test2 as the second argument so that the macro will create a function name of func_test2.

or something like

#define MACRO(foo,postfix,...)  "macro to combine foo and postfix into actual function name"

and then I could use this macro like

MACRO(func, test1, a, b, c);  // will create func_test1(a, b, c);
MACRO(func, test2, i, x);     // will create func_test2(i, x);

There doesn't seem to be a straightforward way to do this.

2
What's the real problem you're trying to solve? - user207421
@EJP I'm trying to call different functions based on compiler flag. - Phonon

2 Answers

6
votes

You can use ## in the macro to concatenate the two parameters as strings. So if your macro is

MACRO(foo, postfix, ...)

you could define it like this

MACRO(foo, postfix, ...) foo##_##postfix(__VA_ARGS__)
                              ^^^ adds an underscore in the middle. Don't include if you
                                 don't want the underscore.

to concatenate foo and postfix with an underscore in between.

Be careful when using arguments that are macros with these types of macros. The argument is pasted without undergoing macro expansion so doing MACRO(foo, MYMACRO, ~) will expand to foo_MYMACRO() instead of the value of MYMACRO.

1
votes

The C preprocessor allows you to use ## to "glue" tokens together.

This means that

#define MACRO(x, y) x ## _ ## y
MACRO(foo, postfix)

will be turned into

foo_postfix