简体   繁体   English

C puzzle ...如何将可变参数传递给宏?

[英]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. 如您所见,上面的代码使用“DBG_INFO”或“DBG_ERROR”等宏来控制调试信息级别。

Now for some reason, I have to replace DBG_LVL() with a new function. 现在由于某种原因,我必须用新函数替换DBG_LVL()

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

The only difference is the debug level is taken as its fisrt parameter. 唯一的区别是调试级别被视为其fisrt参数。 I was thinking: 我刚在想:

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

Of course it failed, because the "stmt" expression includes parentheses around . 当然它失败了,因为“stmt”表达式包括括号 Then I googled around trying to find a way to strip the parentheses, seems there's nothing could help. 然后我用Google搜索试图找到剥离括号的方法,似乎没有什么可以帮助。 I also tried some tricks to pass parameters into "stmt", still failed... :( 我也尝试了一些技巧将参数传递给“stmt”,仍然失败...... :(

Can you help me? 你能帮助我吗?

# define EXPAND_ARGS(...) __VA_ARGS__
# define DBG_LVL(lvl, stmt) myprint(lvl, EXPAND_ARGS stmt);

Don't write this as a macro. 不要把它写成宏。

Write instead an ordinary varargs function: 写一个普通的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);
}

For myprint() , define a similar vamyprint(int lvl, const char *format, va_list ap) as well, and forward the same way. 对于myprint()myprint()定义类似的vamyprint(int lvl, const char *format, va_list ap) ,并以相同的方式转发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM