C ... How to pass variable arguments to a macro?

I'm 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 above code uses macros like DBG_INFO or DBG_ERROR to control the level of debug information.

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 that the debug level is taken as the fisrt parameter. I thought:

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

Of course, this failed because the expression "stmt" contains parentheses around . Then I searched googled around, trying to find a way to remove the parentheses, it seems that nothing can help. I also tried some tricks to pass parameters to "stmt", still failed ...: (

Can you help me?

+5
2
# define EXPAND_ARGS(...) __VA_ARGS__
# define DBG_LVL(lvl, stmt) myprint(lvl, EXPAND_ARGS stmt);
+10

.

varargs:

void DBG_LVL(int level, char *fmt, ...)
{
    if (level < 1) return;

    va_list args;
    va_start(args, fmt);

    vaprintf(fmt, args);

    va_end(args);
}

myprint() vamyprint(int lvl, const char *format, va_list ap) .

+2

All Articles