简体   繁体   English

C:连续宏不起作用

[英]C: Consecutive macros don't work

I have a function that displays a string on the screen. 我有一个在屏幕上显示字符串的函数。 The prototype is dispStrFont(char* str, struct Font font, int x, int y, int color) . 原型是dispStrFont(char* str, struct Font font, int x, int y, int color)

However since it is annoying to type the font, I made a macro #define dispStr(str, x, y, color) dispStrFont(str, normal_font, x, y, color) . 但是,由于键入字体很烦人,所以我创建了一个宏#define dispStr(str, x, y, color) dispStrFont(str, normal_font, x, y, color) Seems to work fine when compiling (no errors). 编译时似乎工作正常(无错误)。

Most of my strings are black, so there's no need for me to type the color. 我的大多数琴弦都是黑色的,因此不需要输入颜色。 So I made the color optional with another macro (placed before the above one): #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) dispStr(str, x, y, 0)

The combination of those two macros give errors, and I don't know why. 这两个宏的组合会产生错误,我不知道为什么。

Header file: 头文件:

#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)"

Main file: 主文件:

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

Why does it behaves that way? 为什么会这样呢? Also, when I comment the second define, it doesn't give me that parenthesis error (but it doesn't compile obviously because it doesn't recognize the dispStr function), so it's the consecutive defines on dispStr(str, x, y) that cause the error. 另外,当我注释第二个定义时,它不会给我括号错误(但由于无法识别dispStr函数而无法编译),因此它是对dispStr(str, x, y)的连续定义) dispStr(str, x, y) ,导致错误。

Edit: ended up modifying the macros to remove the unnecessary combination. 编辑:最终修改宏以删除不必要的组合。 So define dispStr(str, x, y) dispStr(str, x, y, 0) becomes define dispStr(str, x, y) dispStrFont(str, normal_font, x, y, 0) . 因此, define dispStr(str, x, y) dispStr(str, x, y, 0)成为define dispStr(str, x, y) dispStrFont(str, normal_font, x, y, 0) I also had to put that define after the other one, else it still gave me the parenthesis error for some reason. 我还必须将该定义放在另一个之后,否则由于某种原因它仍然给我括号错误。

You can't overload the macros. 您不能重载宏。 Moreover if a macro is invoked already, it is not invoked again. 此外,如果已经调用了宏,则不会再次调用它。

You should give different names to your macro. 您应该给宏命名不同的名称。 Also you can use variadic macro supported as GNU extension and in C99 onwards. 您也可以使用GNU扩展以及C99及更高版本支持的可变参数宏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM