宏定义 [英] macro definition

查看:71
本文介绍了宏定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图定义一个功能如下的宏.调用1没问题,但是调用3提示编译器错误,因为第3个参数不可用.如何定义一个同时支持调用1和调用2的宏?

I tried to define a macro functioned as below. Call 1 has no problem, but Call 2 prompted compiler error because 3rd argument is not available. How to define a macro which support both call 1 and call 2?

#define RDF_LOG(dbglevel, fmt, ...) (rdfDBG(dbglevel, " " fmt, __VA_ARGS__))
void rdfDBG(int dbglevel, const char *fmt, ...) { /* printf debug message */ }

RDF_LOG(kERROR, "Fail to open file %s\n", pinfile); /* Call 1 */
RDF_LOG(kERROR, "Insufficient Memory\n"); /* call 2 , compiler -> error: expected expression before ')' token */

推荐答案

在第二个宏扩展中,您会得到一个额外的逗号,因为在宏定义中,在fmt之后有一个无条件的逗号.

You're getting an extra comma in the second macro expansion, because you have an unconditional comma after fmt in the macro definition.

从宏定义中删除fmt参数似乎可以解决该问题;格式字符串然后成为__VA_ARGS__的一部分:

Dropping the fmt parameter from the macro definition seems to fix the problem; the format string then becomes part of __VA_ARGS__:

#define RDF_LOG(dbglevel, ...) (rdfDBG(dbglevel, " " __VA_ARGS__))
void rdfDBG(int dbglevel, const char *fmt, ...) { /* printf debug message */ }

RDF_LOG(kERROR, "Fail to open file %s\n", pinfile); /* Call 1 */
RDF_LOG(kERROR, "Insufficient Memory\n");

这扩展为:

void rdfDBG(int dbglevel, const char *fmt, ...) { }

(rdfDBG(kERROR, " " "Fail to open file %s\n", pinfile));
(rdfDBG(kERROR, " " "Insufficient Memory\n"));

顺便说一句,看起来" "旨在要求格式为字符串文字(而我的修改版本保留了该格式).您确定要这样做吗?尽管很少见,但使用非文字格式的字符串可能会很有用.

Incidentally, it looks like the " " is intended to require the format to be a string literal (and my modified version preserves this). Are you sure you want to do that? Though it's rare, it can be useful to have a non-literal format string.

这篇关于宏定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆