5

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?

2
  • Always google for what you want, not what you think you want. Same goes for asking people questions. Commented Aug 26, 2011 at 23:45
  • Thanks. You are right. Maybe I should not put in too much subjective opinions when asking questions... Commented Aug 27, 2011 at 0:09

2 Answers 2

10
# define EXPAND_ARGS(...) __VA_ARGS__
# define DBG_LVL(lvl, stmt) myprint(lvl, EXPAND_ARGS stmt);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! It works. This trick is awesome! actually I studied _VA_ARGS_ for a while, but i did't notice it can be used this way... even worse, i tried #define xx((stmt)) stmt, haha, compiler complained a lot.....
2

Don't write this as a macro.

Write instead an ordinary varargs function:

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

    va_list args;
    va_start(args, fmt);

    vaprintf(fmt, args);

    va_end(args);
}

For myprint(), define a similar vamyprint(int lvl, const char *format, va_list ap) as well, and forward the same way.

1 Comment

Yes, that's one way. Thanks. :) but there's some difficulties, because these macros "DBG_INFO" "DBG_ERROR" were widely used in projects, over 20 thousands files... I can't just update all these projects for this reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.