C:连续的宏不起作用

Zez*_*bye 1 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)"
Run Code Online (Sandbox Code Playgroud)

主文件:

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
Run Code Online (Sandbox Code Playgroud)

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

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

Moh*_*ain 7

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

您应该为宏指定不同的名称.您也可以使用支持GNU扩展的variadic宏和C99以上版本.