Vorac Vorac - 9 months ago 158
C Question

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

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 equivalets 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 -stc=c99

Answer Source

Since you can use C99, I'd wrap it in a variadic macro:

#define TM_PRINTF(f_, ...) printf((f_), __VA_ARGS__)
#define TM_SNPRINTF(s_, sz_, f_, ...) snprintf((s_), (sz_), (f_), __VA_ARGS__)

since you didn't say that you have vprintf or something like it. If you do have something like it, you could wrap it in a function like Sergey L has provided in his answer.