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

This sounds a bit like an interview question, but it is actually an actual question.

I am using an embedded platform and only provide this​​ The equivalent of these functions:

> printf()
> snprintf()

In addition, the implementation (and signature) of printf() is likely to change in the near future, so The call to it must reside in a separate module for easy migration in the future.

In view of this, can I wrap the logging call in some function or macro? The goal is that my source code calls THAT_MACRO(“Number of rabbits: %d”,numBunnies); in a thousand places, but only one place to see the call to the above function.

Compiler: arm-gcc -std = c99

Since you can use C99, I wrap it in variadic macro Medium:

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

Because you didn’t say you have vprintf or something similar. If you do have something like this, you can Wrap it in the function provided by Sergey L in his answer.

Edit:

The above TM_PRINTF does not apply to an empty VA_ARGS list.
At least in GCC You can write in:

#define TM_PRINTF(f_, ...) printf((f_), ##__VA_ARGS__)

If __VA_ARGS__ is Empty, the two ## symbols remove the extra comma in front of them.

This sounds a bit like an interview question, but it is actually an actual question.

< /p>

I am using an embedded platform and only provide equivalents of these functions:

> printf()
> snprintf()

In addition , printf() implementation (and signature) is likely to change in the near future, so calls to it must reside in a separate module for easy migration in the future.

Given these, I can Wrap logging calls in some functions or macros? The goal is that my source code calls THAT_MACRO(“Number of rabbits: %d”,numBunnies); in a thousand places, but only one place to see the call to the above function.

Compiler: arm-gcc -std = c99

Since you can use C99, I 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__)

Because you did not say that you have vprintf or something similar. If you do have something like this, you can wrap it in Sergey L in his answer Among the functions provided in.

Edit:

The above TM_PRINTF does not apply to an empty VA_ARGS list.
At least in GCC, you can write:

< /p>

#define TM_PRINTF(f_, ...) printf((f_), ##__VA_ARGS__)

If __VA_ARGS__ is empty, the two ## symbols delete the Extra comma.

Leave a Comment

Your email address will not be published.