#define LOG_MSG(...) 用于调试
下面的代码是如何工作的?
#define ENABLE_DEBUG 1
#if ENABLE_DEBUG
#define LOG_MSG printf
#else
#define LOG_MSG(...)
#endif
How does the following code work?
#define ENABLE_DEBUG 1
#if ENABLE_DEBUG
#define LOG_MSG printf
#else
#define LOG_MSG(...)
#endif
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据
ENABLE_DEBUG
的值,LOG_MSG
要么定义为printf()
的别名,要么定义为无操作宏。这意味着您可以将该值更改为0
以禁用调试。这是一种常见的技术,可以轻松地在显示大量输出的调试版本和安静的发布版本之间切换。这使其成为
printf()
的别名。这将其定义为一个空宏。请注意,这里它有一组括号,这意味着宏需要参数。之后它就什么也没有了,这意味着它会扩展为完全没有。
...
表示该宏可以采用 不同数量的参数。此语法是 C99 扩展,因此它可能不适用于较旧的 C 编译器。结果是
LOG_MSG()
调用将打印一条消息或不执行任何操作,具体取决于是否启用日志记录。无论如何,无论谁编写了这个宏,都可以通过使用
...
语法(他/她显然熟悉)替换第一个定义来做得更好,并打印到 stderr而不是标准输出:Depending on the value of
ENABLE_DEBUG
,LOG_MSG
is either defined to be an alias forprintf()
or it is defined as a no-op macro. It is implied that you can change the value to0
to disable debugging. This is a common technique for making it easy to switch between debugging builds which display lots of output and release builds which are quiet.This makes it an alias for
printf()
.And this defines it as an empty macro. Notice that here it has a set of parentheses, which means the macro takes parameters. It has nothing afterwards which means it expands to absolutely nothing. And the
...
indicates that this macro can take a varying number of arguments. This syntax is a C99 extension so it may not be available on older C compilers.The result is that a
LOG_MSG()
call will either print a message or do nothing depending on whether logging is enabled.For what it's worth, whoever authored this macro could've done a better job by replacing the first definition with one using the
...
syntax (which he/she is clearly familiar with), printing to stderr instead of stdout:这使用预处理器在编译之前更改代码。
如果
ENABLE_DEBUG
被定义为 1,每当预处理器看到它会将其替换为
如果它被定义为 0,或者未定义,它将用任何内容替换它(正如刚刚发布的另一个答案所说) )。
This uses the preprocessor to change code before compilation.
If
ENABLE_DEBUG
is defined as 1, whenever the preprocessor seesIt will replace it with
If it is defined as 0, or not defined it will replace it with nothing (as the other answer that has just been published says).