I tried to define a macro functioned as below. Call 1 has no problem, but Call 2 prompted compiler error because 3rd argument is not available. How to define a macro which support both call 1 and call 2?
#define RDF_LOG(dbglevel, fmt, ...) (rdfDBG(dbglevel, " " fmt, __VA_ARGS__))
void rdfDBG(int dbglevel, const char *fmt, ...) { /* printf debug message */ }
RDF_LOG(kERROR, "Fail to open file %s\n", pinfile); /* Call 1 */
RDF_LOG(kERROR, "Insufficient Memory\n"); /* call 2 , compiler -> error: expected expression before ')' token */
You’re getting an extra comma in the second macro expansion, because you have an unconditional comma after
fmtin the macro definition.Dropping the
fmtparameter from the macro definition seems to fix the problem; the format string then becomes part of__VA_ARGS__:This expands to:
Incidentally, it looks like the
" "is intended to require the format to be a string literal (and my modified version preserves this). Are you sure you want to do that? Though it’s rare, it can be useful to have a non-literal format string.