Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I have a C macro that accepts undefined number of parameters? [duplicate]

Tags:

c

logging

macros

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).

like image 889
errah Avatar asked Jun 11 '12 19:06

errah


2 Answers

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__)
like image 68
ouah Avatar answered Sep 28 '22 12:09

ouah


Yes you can. C99 supports this out of the box.

The syntax looks like:

#define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)

like image 21
David Titarenco Avatar answered Sep 28 '22 12:09

David Titarenco