How to wrap printf() into a function or macro?

Vorac picture Vorac · Dec 17, 2013 · Viewed 70.2k times · Source

This sounds a little like an interview question,but is actually a practical problem.

I am working with an embedded platform, and have available only the equivalents of those functions:

  • printf()
  • snprintf()

Furthermore, the printf() implementation (and signature) is likely to change in the near future, so calls to it have to reside in a separate module, in order to be easy to migrate later.

Given those, can I wrap logging calls in some function or macro? The goal is that my source code calls THAT_MACRO("Number of bunnies: %d", numBunnies); in a thousand places, but calls to the above functions are seen only in one place.

Compiler: arm-gcc -std=c99

Answer

Sergey L. picture Sergey L. · Dec 17, 2013

There are 2 ways to do this:

  1. Variadric macro

    #define my_printf(...) printf(__VA_ARGS__)
    
  2. function that forwards va_args

    #include <stdarg.h>
    #include <stdio.h>
    
    void my_printf(const char *fmt, ...) {
        va_list args;
        va_start(args, fmt);
        vprintf(fmt, args);
        va_end(args);
    }
    

There are also vsnprintf, vfprintf and whatever you can think of in stdio.