Praveen's Blog

An Eternal Quest for Incremental Improvement

A pre-processor macro taking variable length arguments

In C, sometimes you want to write a C pre-processor macro that takes variable length arguments. Let me give you a practical requirement example. The requirement is that a debug log function needs to be written that takes format string and the variables as arguments and produce a debug log with the filename, line numbe and function. It is also desirable that the function/macro argument is kept minimal so that you need not pass some unwanted stuff to the call. I think there is no other easier way than a variable length macro on doing this. The macro would look something like this.

#define FOO_DEBUG( format, ... ) \
    bar_debug ( __FILE__, __LINE__, __FUNCTION__, format, ## __VA_ARGS__ )

A C function bar_debug can then be written with the fingerprint that matches above and the variable arguments can be parsed in the traditional way.

The key hint here is the token pasting of __VA_ARGS__