简体   繁体   中英

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) .

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) . 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) .

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.

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) . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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