Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when defining a stringising macro with __VA_ARGS__

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__)
like image 410
Marco Scannadinari Avatar asked Sep 23 '13 20:09

Marco Scannadinari


People also ask

What is __ Va_args __ C++?

macro expansion possible specifying __VA_ARGS__ The '...' in the parameter list represents the variadic data when the macro is invoked and the __VA_ARGS__ in the expansion represents the variadic data in the expansion of the macro. Variadic data is of the form of 1 or more preprocessor tokens separated by commas.

What is #__ Va_args __?

Preprocessor: __VA_ARGS__ : count arguments This is an attempt to define a few variadic macros that can be used to count the number of arguments given.


1 Answers

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.

like image 151
cnicutar Avatar answered Sep 18 '22 12:09

cnicutar