如何包装的printf()成一个函数或宏? [英] How to wrap printf() into a function or macro?
问题描述
这听起来像一个面试问题了一点,但实际上是一个实际问题。
This sounds a little like an interview question,but is actually a practical problem.
我与嵌入式平台的工作,并具备只有这些功能的equivalets:
I am working with an embedded platform, and have available only the equivalets of those functions:
- 的printf()
- 的snprintf()
此外,printf()的实现(和签名)很可能在不久的将来发生变化,所以将它的调用必须驻留在独立的模块中,为了易于以后迁移
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.
鉴于这些,我可以换一些功能或宏记录通话。我们的目标是我的源$ C $ C调用 THAT_MACRO(兔子数:%d,numBunnies);
在千元地方,但调用上述功能只有在一个地方看到的。
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.
编译器臂GCC -STC = C99
Compiler arm-gcc -stc=c99
推荐答案
由于可以使用C99,我将它包装在一个可变参数宏:
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__)
因为你没有说你有 vprintf
或类似的东西。如果你有类似的东西,你可以像谢尔盖L时他的回答已经提供了一个功能包裹。
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.
这篇关于如何包装的printf()成一个函数或宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!