Macros with variable length arguments in C

I want to do a simple logging hack, so that I can turn on and off debug information in this app I’m working on by just adjusting the log level. log4c does this, but they don’t claim Windows support and I’m too lazy to untar their source.

A simple solution for logging in C would be to just create my own printf basically that takes a log level as an argument and then passes the arguments onto printf based on the log level passed. I’m too lazy to implement anything tho..

An even simpler solution would be to just set up some #define’d macros that map debug calls to printf’s based on the log level set at compile time. OK, this I can handle.

In order to call printf and retain printf’s variable number of arguments stuff however, you need to be able to write macros that support a variable number of arguments. According to this page “variadic macros” weren’t standardized until ISO ’99 C. Since VS.NET uses some strange unknown variant of C, I would need to find a workaround that worked in VS.NET. (Truth: VS.NET might very well support ISO ’99 C, but I’m too lazy to figure out how to enable it).

So here’s how you do variable number of argument macros in VS.NET, taken from this post:

#define myprintf ::printf

This simply aliases the printf() function to myprintf(). To do log level debugging, I did something like this:

#define debug_fine ::printf
#define debug_fine 1 ? (void)0 : ::printf

This maps debugf to printf when LDEBUG_FINE is true, otherwise it removes calls to debug_fine.

I think. Anyways, it works, and, well, I’m too lazy to figure out why. I have real code to be writing. 🙂

Leave a Reply