如何将 printf() 包装到函数或宏中? [英] How to wrap printf() into a function or macro?
问题描述
这听起来像是一个面试问题,但实际上是一个实际问题.
This might sound 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()
此外,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.
鉴于此,我可以将日志调用包装在某个函数或宏中吗?目标是我的源代码在一千个地方调用了 THAT_MACRO("Number of bunnies: %d", numBunnies);
,但只能在一个地方看到对上述函数的调用.
Given that, 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 a single place.
编译器:arm-gcc -std=c99
只是提一下,但在 2000 年的最佳实践之后,而且可能更早,内联函数由于多种原因远比宏好.
just to mention, but post 2000 best practices and probably a lot earlier, inline functions are far better than macros for numerous reasons.
推荐答案
既然你可以使用 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
或类似的东西.如果您确实有类似的东西,您可以将其包装在 Sergey 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.
上述 TM_PRINTF 不适用于空的 VA_ARGS 列表.至少在 GCC 中可以这样写:
The above TM_PRINTF does not work with an empty VA_ARGS list. At least in GCC it is possible to write:
#define TM_PRINTF(f_, ...) printf((f_), ##__VA_ARGS__)
如果 __VA_ARGS__
为空,两个 ## 符号会删除它们前面多余的逗号.
The two ## signs remove the excess comma in front of them them if __VA_ARGS__
is empty.
这篇关于如何将 printf() 包装到函数或宏中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!