Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C难题…如何将可变参数传递到宏中?_C_C Preprocessor_Variadic Functions - Fatal编程技术网

C难题…如何将可变参数传递到宏中?

C难题…如何将可变参数传递到宏中?,c,c-preprocessor,variadic-functions,C,C Preprocessor,Variadic Functions,我被困在这里 #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"))

我被困在这里

#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;
}
唯一的区别是调试级别作为其第一个参数。 我在想:

#define DBG_LVL(lvl, stmt) myprint(lvl, stmt)
当然它失败了,因为“stmt”表达式包含括号。 然后我在谷歌上四处搜索,试图找到一种去除括号的方法,似乎没有什么能帮上忙。 我还尝试了一些将参数传递到“stmt”的技巧,但仍然失败了…:(


你能帮我吗?

不要把它写成宏

# define EXPAND_ARGS(...) __VA_ARGS__
# define DBG_LVL(lvl, stmt) myprint(lvl, EXPAND_ARGS stmt);
改为编写普通的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);
}
void DBG\u LVL(整数级,字符*fmt,…)
{
如果(级别<1)返回;
va_列表参数;
va_启动(参数、fmt);
vaprintf(fmt,args);
va_端(args);
}

对于
myprint()
,定义一个类似的
vamyprint(int lvl,const char*格式,va_list ap)
也一样,并以同样的方式前进。

总是搜索你想要的,而不是你认为你想要的。问别人问题也是如此。谢谢。你是对的。也许我在提问时不应该发表太多主观意见……是的,这是一种方式。谢谢。:)但是有一些困难,因为这些宏“DBG_INFO”“DBG_错误”在项目中被广泛使用,超过2万个文件…我不能仅仅因为这个原因更新所有这些项目。是的!它很有效。这个技巧非常棒!实际上我研究了一段时间,但我没有注意到它可以这样使用…更糟糕的是,我尝试了
\define xx((stmt))stmt
,哈哈,编译器抱怨了很多。。。。。
void DBG_LVL(int level, char *fmt, ...)
{
    if (level < 1) return;

    va_list args;
    va_start(args, fmt);

    vaprintf(fmt, args);

    va_end(args);
}