Search code examples
cc-preprocessorpreprocessor

How can I define some arguments of a C macro as another macro?


Consider the macro

#define IP4_ADDR(ipaddr, a,b,c,d)  (ipaddr)->addr = PP_HTONL(LWIP_MAKEU32(a,b,c,d))

I would like to define the arguments a,b,c,d in another macro. So I have done this:

#define DEBUG_HOST_IP4 192, 168, 0, 123

IP4_ADDR(&debug_host, 192, 168, 0, 123 );
IP4_ADDR(&debug_host, DEBUG_HOST_IP4 );

The first call to IP4_ADDR compiles succesfully, while the second one fails with

error: macro "IP4_ADDR" requires 5 arguments, but only 2 given
IP4_ADDR(&debug_host, DEBUG_HOST_IP4 );

Is there a way to make DEBUG_HOST_IP4 expand properly, so the IP4_ADDR macro can work as intended?

EDIT: The IP4_ADDR macro comes from a third-party library, which I would rather not touch, and risk breaking somebody else's code. Of course, implementing my own version is an option.


Solution

  • If you can't alter IP4_ADDR, this is still pretty easy; just wrap it:

    #define MY_IP4_ADDR(...) IP4_ADDR(__VA_ARGS__)
    

    During the translation (which just moves all of the arguments over, whatever they are), any macros will expand. Then just use your wrapped version in the code.

      MY_IP4_ADDR(&debug_host, 192, 168, 0, 123 );
      MY_IP4_ADDR(&debug_host, DEBUG_HOST_IP4 );
    

    And you should be good to go.