Variable length C macros

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




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/Bookmark

Tags: , ,

5 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:

    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:

  4. Err, I may be missing something, but following code always worked for me in GCC:

    #define FORMAT(level,format,args …) “%-6s [%s] “format, #level, logger->name.c_str(), ##args


    #define macro(args …) call_function(##args)

    (I see Torbjörn provided link for it)

Leave a Reply

To stop spam, please answer this simple question
What OS do we make games for

Please note: This site is fully moderated