Variable length C macros

By Michael Simms (CEO and head of Development)
Saturday, May 30th, 2009

Something that came up in porting X2 and X3 is that Visual Studio in Windows handles variable length macros, and as far as we could see, GCC didnt.

This means that in gcc, if you wanted to create a define that would do a job and report where it was called from, you would need to do something like:

void mydebug(const char *file,int line,const char *fmt,...)

#define DEBUGOUT1(x) mydebug(__FILE__,__LINE__,x)
#define DEBUGOUT2(x,y) mydebug(__FILE__,__LINE__,x,y)
#define DEBUGOUT3(x,y,z) mydebug(__FILE__,__LINE__,x,y,z)

and so on…

However, there is a solution which does the job, which we found after a fair amount of investigation. The recommended method would be

#define DEBUGOUT(x,y...) mydebug(__FILE__,__LINE__,x,y)

Which will work, but only if you actually add a second parameter to the DEBUGOUT call. Without, it will expand

DEBUGOUT(x)

to

mydebug(__FILE__,__LINE__,x,)

which will obviously fail to compile. To fix this, simply bear in mind that … in the macro just means everything else, so you can do

#define DEBUGOUT(x...) mydebug(__FILE__,__LINE__,x)

which then works with single and multiple values in macros, x becomes the fmt AND the … for the mydebug .

Share/Save/Bookmark

Tags: , ,

4 Responses to “Variable length C macros”

  1. RK says:

    Typo: “This means that in gcc, is you wanted to create a define…”
    “is” should be “if” in this sentence.

    Feel free to Moderate this comment into oblivion once you’ve fixed the typo. :)

  2. Max says:

    Quite good that you find out about these solutions and even better that you release them, might come in handy one day when someone is doing something similar.
    The main problem in coding is actually to find out about all the capabilities a language has to offer.
    Actually that seems to be the main problem with many things.
    Most of the time you just don’t know that certain things are allowed.

  3. Torbjörn Andersson says:

    It should perhaps be pointed out that this form of variadic macros is a GCC extension. Nothing wrong with that, but I think it’s good to be aware of it. It’s been there for as long as I can remember, and I might even have used it once or twice myself:

    http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Variadic-Macros.html

    The CPP manual has some more information, but I haven’t had the time to digest it. There does seem to be a couple of ways of dealing with the trailing comma, but unfortunately they too are GCC extensions:

    http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html

Leave a Reply

Enter this code