Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C puzzle...How Can I pass variadic arguments into a macro?

I got stuck here...

#include <stdio.h>

#define DBG_LVL(lvl, stmt) \
do{ \
    if(lvl>1)  printf stmt; \
}while(0)

#define DBG_INFO(stmt)   DBG_LVL(1, stmt)
#define DBG_ERROR(stmt)  DBG_LVL(2, stmt)


int main()
{
    DBG_INFO(("hello, %s!\n", "world"));
    DBG_ERROR(("crazy, %s!\n", "world"));
    return 0;
}

As you can see, the code above uses macros like "DBG_INFO" or "DBG_ERROR" to control debug information level.

Now for some reason, I have to replace DBG_LVL() with a new function.

void myprint(int lvl, const char * format, ...);

The only difference is the debug level is taken as its fisrt parameter. I was thinking:

#define DBG_LVL(lvl, stmt) myprint(lvl, stmt)

Of course it failed, because the "stmt" expression includes parentheses around. Then I googled around trying to find a way to strip the parentheses, seems there's nothing could help. I also tried some tricks to pass parameters into "stmt", still failed... :(

Can you help me?

like image 572
kumo Avatar asked Aug 26 '11 23:08

kumo


1 Answers

# define EXPAND_ARGS(...) __VA_ARGS__
# define DBG_LVL(lvl, stmt) myprint(lvl, EXPAND_ARGS stmt);
like image 183
James McNellis Avatar answered Oct 20 '22 00:10

James McNellis