就像变参函数那样,gcc里的宏(Macros)也可以定义不定个数的参数,主要就是配合变参函数使用。例如:
#define eprintf(...) fprintf (stderr, __VA_ARGS__)
注意:这里是两个下划线__.
使用时:
eprintf ("%s:%d: ", input_file, lineno)
==> fprintf (stderr, "%s:%d: ", input_file, lineno)
除了使用gcc提供的__VA_ARGS__代替变参外,我们还可以给参数起名字,方法是在”…”之前写上名字,如:
#define eprintf(args...) fprintf (stderr, args)
这里有一个问题,例如下面:
#define eprintf(format, ...) fprintf (stderr, format, __VA_ARGS__)
eprintf ("success!\n")
==> fprintf(stderr, "success!\n", ); // 问题:这里多了个逗号!
这样肯定是不行的,因此,gcc还为此提供了”##”符号。##符号在 逗号 和 参数名 之间时不做连字符作用,而作为变参宏的特别用处,如下:
#define eprintf(format, ...) fprintf (stderr, format, ##__VA_ARGS__)
eprintf ("success!\n")
==> fprintf(stderr, "success!\n"); // aha! 这样就OK了!
这个已经是C99标准了,并且gcc能很好的支持,只有一点要注意的:
Variadic macros are a new feature in C99. GNU CPP has supported them for a long time, but only with a named variable argument (`args…’, not `…’ and __VA_ARGS__). If you are concerned with portability to previous versions of GCC, you should use only named variable arguments. On the other hand, if you are concerned with portability to other conforming implementations of C99, you should use only __VA_ARGS__.
Recent Comments