gpt4 book ai didi

c - 为什么我的简单 C 宏不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 03:31:15 25 4
gpt4 key购买 nike

我想制作一个像这样调用 printf() 两次的简单宏

#ifdef ENABLE_DEBUGPRINTF
#define DEBUGPRINTF(msg) printf("At sim_time = %f:", sim_time); printf(msg);
#else
#define DEBUGPRINTF(msg) //evalutes to nothing
#endif

现在当我打电话

DEBUGPRINTF("Processed event type: %d with value %f\n", id, data)

它正确地打印了第一部分“At sime_time = ...”,但后半部分“Processed events ...”错误地打印了 id 和 data 的值。

同时

printf("Processed event type: %d with value %f\n", id, data);

正确打印值。

当我尝试通过准确写出我认为宏的计算结果来执行它时,我做到了。

printf("At sim_time = %f:", sim_time); printf("Processed event type: %d with value %f\n", id, data);

这会正确打印所有内容!那么,为什么我的宏不对此进行评估?

最佳答案

因为您想要并且正在使用常规 printf 的全部灵 active ,所以您需要的是带有 variadic 参数的宏:

#ifdef ENABLE_DEBUGPRINTF
#define DEBUGPRINTF(msg...) \
printf("At sim_time = %f:", sim_time); printf(msg);
#else
#define DEBUGPRINTF(msg...) /*evalutes to nothing*/
#endif

我以前做过很多次,我建议用 do { } while (0) 封装:

#ifdef ENABLE_DEBUGPRINTF
#define DEBUGPRINTF(msg...) \
do { \
printf("At sim_time = %f:", sim_time); \
printf(msg); \
} while (0)
#else
#define DEBUGPRINTF(msg...) //evalutes to nothing
#endif

这使您可以执行以下操作:

if (showit)
DEBUGPRINTF("hit the showit point -- showit=%d\n",showit);

因此,使用宏的代码不必知道它实际上是两个语句[或没有]


更新:

DEBUGPRINTF(msg...) is not standard compliant, but some legacy compiler extension. You missed a comma before the ellipsis.

也许吧,但就我个人而言,我仍然更喜欢它,并且已经在生产代码中使用了 10 多年。

但是,对于那些可能希望使用替代方法的人来说,这里有一些资源:

  1. https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html
  2. https://en.wikipedia.org/wiki/Variadic_macro

关于c - 为什么我的简单 C 宏不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com