Reputation: 1884
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__)
Upvotes: 13
Views: 15916
Reputation: 344
For C toolchains that support C++20 macros, __VA_OPT__
is a more portable solution.
#define DBG(format, ...) printf("DEBUG: " #format "\n" __VA_OPT__(,) __VA_ARGS__)
NOTE: There is no comma between "\n"
and __VA_OPT__
From the GNU GCC manual:
C++20 introduces the VA_OPT function macro. This macro may only appear in the definition of a variadic macro. If the variable argument has any tokens, then a VA_OPT invocation expands to its argument; but if the variable argument does not have any tokens, the VA_OPT expands to nothing:
#define eprintf(format, ...) fprintf (stderr, format __VA_OPT__(,) __VA_ARGS__)
VA_OPT is also available in GNU C and GNU C++.
Upvotes: 0
Reputation: 28900
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);
Upvotes: 0
Reputation: 182714
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.
Upvotes: 24
Reputation: 4614
Check out this on MSDN. It contains info on Variadic Macros, which is what you are using.
Upvotes: -1