0

I have been given a library that defines the following macros:

#define FOO_0(A, B) (A + B)
#define FOO_1(A, B) (A - B)

Now I'd like to create a new macro MY_FOO that takes a third argument x and use it build the name of the macro to be called (e.g. FOO_<x>)

Here is my experiment:

#define MY_FOO(X, A, B) FOO_## X ##(A, B)

However, when I try to use it in my code:

int main(void) {
    int a = 2, b = 3, x = 0;
    printf("FOO_%d(%d, %d) = %d", x, a, b, MY_FOO(x, a, b));
    return 0;
}

I get the following error:

prog.c: In function ‘main’:
prog.c:6:25: error: pasting "FOO_x" and "(" does not give a valid preprocessing token
 #define MY_FOO(X, A, B) FOO_## X ##(A, B)
                         ^
prog.c:11:41: note: in expansion of macro ‘MY_FOO’
  printf("FOO_%d(%d, %d) = %d", x, a, b, MY_FOO(x, a, b));
                                         ^~~~~~
prog.c:6:25: warning: implicit declaration of function ‘FOO_x’ [-Wimplicit-function-declaration]
 #define MY_FOO(X, A, B) FOO_## X ##(A, B)
                         ^
prog.c:11:41: note: in expansion of macro ‘MY_FOO’
  printf("FOO_%d(%d, %d) = %d", x, a, b, MY_FOO(x, a, b));
                                         ^~~~~~

Is there a way to workaround this?

3
  • 2
    The second ## is not required. Commented Aug 8, 2017 at 1:26
  • 1
    In C, there should never be a need to create macros with completely variable names. Macro names are for the programmer, not for the program. If you somehow come up with such a need still, you should rather run an external script that generates the C code. Commented Aug 8, 2017 at 9:52
  • Generating the code proposed by @bipll in the post below automatically could actually be a very good idea because I have to use the same pattern for a lot of macros Commented Aug 8, 2017 at 17:07

1 Answer 1

4

If you really need to turn run-time values into macro names, you'll have to do it on your own:

switch(x) {
    case 0: printf("FOO_0(%d, %d) = %d", a, b, FOO_0(a, b));
            break;
}

You can even make it slightly more advanced with local syntax-defs:

switch(x) {
#define CASE(x) case x: printf("FOO_" #x "(%d, %d) = %d", a, b, FOO_ ## x(a, b)); \
                        break
    CASE(0);
#undef CASE
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! The distinction between run-time and compile-time value is probably the key to this problem.
Even more than that, macros are parse-time values, before the compilation itself. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.