1

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.

Zezombye
  • 321
  • 4
  • 16
  • Did you try switching the orders? – Nic Jun 23 '16 at 06:03
  • If I switch the defines it doesn't work because then `dispStr(str, x, y)` is replaced by `dispStr(str, x, y, 0)` but not then replaced by `dispStrFont`. – Zezombye Jun 23 '16 at 06:05
  • Oh, right. Sorry, I had a brainfart. – Nic Jun 23 '16 at 06:06
  • 1
    Possible duplicate of [Overloading Macro on Number of Arguments](http://stackoverflow.com/questions/11761703/overloading-macro-on-number-of-arguments) – LPs Jun 23 '16 at 06:09
  • Don't give the macros the same name? What made you think that was a good idea for any purpose? It's like posting on some parent guidance forums: "I named all my 5 kids Bob, but I have a problem: they all reply at once when I call for Bob. What should I do?" – Lundin Jun 23 '16 at 06:41

1 Answers1

7

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.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100