c - C语言中如何用宏替换函数

标签 c macros

有时,在我从 Linux 驱动程序借用的 C 代码中,我想将一些宏更改为可以在我的环境中使用的函数。但前面的宏可以接受 3 或 4 个参数。
例如,如果我想替换

SMSC_TRACE(pdata, probe, "Driver Parameters:");   // 3 arguments  

进入

printf("Driver Parameters:");  

并替换

SMSC_TRACE(pdata, probe, "LAN base: 0x%08lX", (unsigned long)pdata->ioaddr); // 4 arguments  

进入

printf("LAN base: 0x%08lX", (unsigned long)pdata->ioaddr);  

我该怎么做?我试过了

#define SMSC_TRACE((a), (b), (c)) printf((c))  
#define SMSC_TRACE((a), (b), (c), (d)) printf((c), (d))  

但似乎不起作用。似乎只有最后一个生效。

编辑:这似乎是可能的。

#define SMSC_TRACE(pdata, nlevel, fmt, args...) printf(fmt "\n", ##args)

最佳答案

您可以使用variadic macro来做到这一点,它采用可变数量的参数:

#define SMSC_TRACE(a,b,...) printf(__VA_ARGS__)

如果你想让这个宏执行多个语句,那么你需要一个do/while(0)

例如:

#define SMSC_TRACE(a,b,...) \
do                          \
{                           \
    printf("%c\n",a);       \
    printf("%d\n",b);       \
    printf(__VA_ARGS__);    \
}                           \
while (0)

关于c - C语言中如何用宏替换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29650633/

相关文章:

macros - 在 Lisp 中,作为 push 是对 cons 的追加是什么?

macros - 在 Common Lisp 中,如何定义一个扩展为空的宏(而不是 `nil` )?

c - 汇编器到 C 的转换 INCF 和 CPFSLT

使用 GNU 编译时 Code Composer Studio 跳过断点

c - 用C语言构建链表

objective-c - 我可以在 C 宏中使用 #if 指令吗?

c - 如何使用按位运算符、掩码来查找一个数字是否是另一个数字的倍数?

c - 一元运算符如何在 C 中工作,您不能预递增零

macros - Define 和 let w.r.t. 之间的区别语法规则关键字

string - SPSS 宏 - DEFINE 中的字符串操作 - !ENDDEFINE