C:连续的宏不起作用

时间:2016-06-23 06:01:40

标签: c macros

我有一个在屏幕上显示字符串的功能。原型是dispStrFont(char* str, struct Font font, int x, int y, int color)

然而,由于输入字体很烦人,我制作了一个宏#define dispStr(str, x, y, color) dispStrFont(str, normal_font, x, y, color)。编译时似乎工作正常(没有错误)。

我的大部分字符串都是黑色的,因此我无需输入颜色。所以我用另一个宏(放在上面的宏之前)使颜色可选:#define dispStr(str, x, y) dispStr(str, x, y, 0)

这两个宏的组合会产生错误,我不知道为什么。

标题文件:

#define dispStr(str, x, y) dispStr(str, x, y, 0)
#define dispStr(str, x, y, color) dispStrFont(str, normal_font, x, y, color)
//the define above gives me a warning: "Incompatible redefinition of macro "dispStr" (declared at line 1)"

主档案:

dispStr("test", x, y) //gives me an error, saying there's an illegal token ')'
                      //also gives me a warning "Too few arguments in macro invocation"
dispStr("test", x, y, 0) //compiles fine

为什么它会这样?另外,当我评论第二个定义时,它没有给我那个括号错误(但它没有明显编译,因为它不能识别dispStr函数),所以它是{{1上的连续定义导致错误。

编辑:最后修改宏以删除不必要的组合。因此dispStr(str, x, y)变为define dispStr(str, x, y) dispStr(str, x, y, 0)。我还必须将该定义放在另一个之后,否则由于某种原因它仍然给出了括号错误。

1 个答案:

答案 0 :(得分:7)

您不能重载宏。此外,如果已经调用了宏,则不会再次调用它。

您应该为宏指定不同的名称。此外,您可以使用variadic macro支持GNU扩展,也可以使用C99。