Error when defining a stringising macro with __VA_ARGS__
Asked Answered
B

3

12

I have been trying to implement a function macro in C that prepends "DEBUG: ", to the argument, and passes its arguments to printf:

#define DBG(format, ...) printf("DEBUG: " #format "\n", __VA_ARGS__)

This gives me this error in gcc:

src/include/debug.h:4:70: error: expected expression before ‘)’ token
#define DBG(format, ...) printf("DEBUG: " #format "\n", __VA_ARGS__)
                                                                   ^

Supposedly, it should stringise format, and pass its variable arguments to printf, but so far I can't get past this error.


EDIT

After giving up on stringising arguments, and double-hashing (##) __VA_ARGS__ I now have this error:

src/lib/cmdlineutils.c: In function ‘version’:
src/lib/cmdlineutils.c:56:17: warning: ISO C99 requires rest arguments to be used [enabled by default]
  DBG("version()");

Should I be placing a comma after the argument?

DBG("version()",);  // ?

For reference, DBG() now looks like this:

#define DBG(format, ...) printf("DEBUG: " format "\n", ##__VA_ARGS__)
Brunswick answered 23/9, 2013 at 20:18 Comment(2)
Works for me on gcc, which compiler did you use? Can you try putting a space between the # and format?Bedad
$ gcc --version: gcc (GCC) 4.8.1 20130725 (prerelease)Brunswick
V
23

This happens unless there's at least one variable argument. You can try this GNU extension to fix it:

#define DBG(format, ...) printf("DEBUG: " #format "\n", ##__VA_ARGS__)
                                                        ^^

As explained in the GNU doc:

[if] the variable argument is left out when the macro is used, then the comma before the ‘##’ will be deleted.

Viridescent answered 23/9, 2013 at 20:28 Comment(3)
@marcoms Pretty strange, are you sure you copied the line correctly ?Viridescent
the only character that is missing from my defenition is the hash (#) before format, as I decided to stringise the argument when calling it myself, to rule out one possible cause, i.e.: DBG("printf()");Brunswick
@cnicurar - I'm going to assume those warnings are just the compiler warning me that the double-hashes aren't standard, so you can have an acceptBrunswick
A
0

Check out this on MSDN. It contains info on Variadic Macros, which is what you are using.

Adamek answered 23/9, 2013 at 20:22 Comment(0)
B
0

Why do you need to stringise format, it can stay as is, just treat it as a string when using the macro.

The error, as cnicutar propsed can be solved with adding '##' before the VA_ARGS

#define DBG(format, ...) printf("DEBUG: " format "\n", ##__VA_ARGS__)

Usage example:

DBG("%d - %s", a,b);
Bidle answered 23/9, 2013 at 20:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.