7

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

Community
  • 1
  • 1
errah
  • 303
  • 3
  • 9

4 Answers4

7

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__)
ouah
  • 142,963
  • 15
  • 272
  • 331
2

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

The syntax looks like:

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

David Titarenco
  • 32,662
  • 13
  • 66
  • 111
0

You can use an ellipsis to define a macro which takes a variable number of arguments:

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

http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/4/html/Using_the_GNU_Compiler_Collection/variadic-macros.html

embedded.kyle
  • 10,976
  • 5
  • 37
  • 56