【问题标题】:C: Consecutive macros don't workC:连续的宏不起作用
【发布时间】:2016-06-23 06:01:40
【问题描述】:

我有一个在屏幕上显示字符串的函数。原型是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 函数),所以它是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)。我还必须将该定义放在另一个定义之后,否则由于某种原因它仍然给了我括号错误。

【问题讨论】:

  • 您是否尝试过切换订单?
  • 如果我切换定义它不起作用,因为 dispStr(str, x, y) 被 dispStr(str, x, y, 0) 替换,但没有被 dispStrFont 替换。
  • 哦,对了。抱歉,我脑子有问题。
  • 不要给宏同名?是什么让你认为这是一个好主意?这就像在一些家长指导论坛上发帖:“我将所有 5 个孩子都命名为 Bob,但我有一个问题:当我打电话给 Bob 时,他们都会立即回复。我该怎么办?”

标签: c macros


【解决方案1】:

您不能重载宏。此外,如果一个宏已经被调用,它就不会再次被调用。

您应该为宏指定不同的名称。你也可以使用variadic macro 支持作为 GNU 扩展和 C99 及更高版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多