cmacrosgcc4.6

(C99)Expand a macro in a different macro


I have a function in my program that takes 3 arguments. Some times in the code there is a macro defining 2 of these parameters.

So this:

void func(int x, int y, int z){...}

Can be invoked like this:

#define PAR 10,20
int z = 3;
func(PAR, z);

Now, I need to change my code so that the function is called like a macro for another function.

#define func(X,Y,Z) func2(X,Y,Z,#Z)

This works fine if X and Y are really passed as variables. Is there any way to make it work also with the macro PAR?

I'm using GCC 4.6


Solution

  • You can do this with an extra level of indirection, (ab)using variadic macros:

    #include <stdio.h>
    #define PAR 2,3
    #define F(...) G(__VA_ARGS__)
    #define G(a,b,c) H(a,b,c)
    void H(int a, int b, int c) {
      printf("%d %d %d\n", a , b, c);
    }
    int main() {
      F(PAR, 42);
      return 0;
    }
    

    There is probably a better solution for the underlying problem.