Possible Duplicate:
How to make a variadic macro (variable number of arguments)
I want to have a log macro in basic C which accepts arguments similar to printf
and logs them. However, I want how it's logged (log level, file vs stderr
, etc.) to be something set at compile time, not runtime; with the method doing nothing and hopefully being optimized out of the code if I set parameters to ignore low level logging.
So far I have a macro which is defined based off of a parameter defined at compile time. If the parameter is defined logging goes to my log method (to log to files) otherwise it goes to stderr
. However, I can only pass a string into this macro. The log method is capable of taking an indefinite number of arguments and works using printf
syntax. I want to know if there is a way to set my macro up so it will pass an indefinite number of arguments to the log file?
And since I suspect the answer is that I can't do that is there another method of achieving what I want in basic C (I can't use C++ or boost).
C99 have macros that can accept a variable number of arguments. They are called variadic macros.
http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html
Example:
#define eprintf(...) fprintf (stderr, __VA_ARGS__)
#define dfprintf(stream, ...) fprintf(stream, "DEBUG: " __VA_ARGS__)
Yes you can. C99 supports this out of the box.
The syntax looks like:
#define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With