Error defining string macro using __VA_ARGS__

I am trying to implement a function macro in C that adds "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__) ^ 

Presumably, it should scribble the format and pass arguments to the variable printf, but so far I can not get through this error.


EDIT

After discarding the building 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 put a comma after the argument?

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

For reference, DBG () now looks like this:

 #define DBG(format, ...) printf("DEBUG: " format "\n", ##__VA_ARGS__) 
+6
source share
3 answers

This happens if there is not 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 document :

[if] the argument of the variable is not taken into account when using the macro, then the comma before '## will be deleted.

+8
source

Check it out on MSDN. It contains information about the Variadic Matrices that you use.

0
source

Why do you need a string format, it can remain as it is, just treat it as a string when using a macro.

Error, since cnicutar recped can be resolved with the addition of '##' before VA_ARGS

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

Usage example:

 DBG("%d - %s", a,b); 
0
source

Source: https://habr.com/ru/post/954450/


All Articles