Reputation: 5929
Sometimes, in a C code I borrowed from a linux driver, I want to change some macros into a function that I can use in my environment. But this previous macro can take 3 or 4 arguments.
For example, if I want to substite
SMSC_TRACE(pdata, probe, "Driver Parameters:"); // 3 arguments
into
printf("Driver Parameters:");
and substitute
SMSC_TRACE(pdata, probe, "LAN base: 0x%08lX", (unsigned long)pdata->ioaddr); // 4 arguments
into
printf("LAN base: 0x%08lX", (unsigned long)pdata->ioaddr);
How do I do that? I tried
#define SMSC_TRACE((a), (b), (c)) printf((c))
#define SMSC_TRACE((a), (b), (c), (d)) printf((c), (d))
but it doesn't seem to work. Only the last one seems to take effect.
EDIT: this seems it maybe.
#define SMSC_TRACE(pdata, nlevel, fmt, args...) printf(fmt "\n", ##args)
Upvotes: 2
Views: 405
Reputation: 30136
You can do it with a variadic macro, which takes a variable number of arguments:
#define SMSC_TRACE(a,b,...) printf(__VA_ARGS__)
If you want this macro to execute multiple statements, then you need a do/while(0)
.
For example:
#define SMSC_TRACE(a,b,...) \
do \
{ \
printf("%c\n",a); \
printf("%d\n",b); \
printf(__VA_ARGS__); \
} \
while (0)
Upvotes: 5