【问题标题】:Can macros accept types?宏可以接受类型吗?
【发布时间】:2015-01-28 07:18:37
【问题描述】:

除非我的理解不正确,否则下面的宏

int i; // for loop
const char* ctype; // proprietary type string
void** pool = malloc(sizeof(void*) * (nexpected - 1));
size_t poolc = 0;

#define SET(type, fn) type* v = (pool[poolc++] = malloc(sizeof(type)));         \
    *v = (type) fn(L, i)
#define CHECK(chr, type, fn) case chr:                                          \
    SET(type, fn);                                                              \
    break

switch (ctype[0]) {
  CHECK('c', char, lua_tonumber);
}

应该扩展到

int i; // for loop
const char* ctype; // proprietary type string
void** pool = malloc(sizeof(void*) * (nexpected - 1));
size_t poolc = 0;

switch (ctype[0]) {
  case 'c':
    char* v = (pool[poolc++] = malloc(sizeof(char)));
    *v = (char) lua_tonumber(L, i);
    break;
}

但在编译后,我得到:

src/lua/snip.m:185:16: error: expected expression
    CHECK('c', char, lua_tonumber);
               ^
src/lua/snip.m:181:9: note: expanded from macro 'CHECK'
    SET(type, fn);                                                              \
        ^
src/lua/snip.m:178:23: note: expanded from macro 'SET'
#define SET(type, fn) type* v = (pool[poolc++] = malloc(sizeof(type)));         \
                      ^
src/lua/snip.m:185:5: error: use of undeclared identifier 'v'
    CHECK('c', char, lua_tonumber);
    ^
src/lua/snip.m:181:5: note: expanded from macro 'CHECK'
    SET(type, fn);                                                              \
    ^
src/lua/snip.m:179:6: note: expanded from macro 'SET'
    *v = (type) fn(L, i)
     ^
2 errors generated.

这里发生了什么?预处理器不是文字文本替换引擎吗?为什么要尝试评估表达式?

请记住,虽然这看起来像直接的 C,但它实际上是 C11 标准下的 clang Objective C(注意 .m)。不确定这是否有什么不同。

我不知道如何在不扩展每个条目的代码的情况下继续。

【问题讨论】:

  • @Lundin 如果您阅读 OP,它会告诉您。
  • C11 标签应该用于使用特定于 C11 标准的功能的问题,这里不是这种情况。如果您阅读标签 wiki,它会告诉您。
  • @Lundin 我很清楚标签是如何工作的。我正在根据 C11 标准进行编译。回答后,很明显不是C11的问题。但是,当我问我不知道 C11 是否改变了宏的工作方式时。这与当时的问题有关。欢迎您搜索有关 C/C++ 相关的“标签纳粹”讨论的 Meta。
  • 您总是可以从您的帖子中远程删除标签,而不是离开 snide cmets。这不是世界末日。
  • @Lundin 如果您查看 OP,您会看到我做到了。感谢您的关心。

标签: objective-c c c-preprocessor


【解决方案1】:

你的理解是正确的!但是您遇到了 C 语言的怪癖。 A label, including a case label, must be followed by an expression, not a variable declaration.

您可以通过在case 之后插入一个空语句(例如0;)来解决此问题,或者将case 正文括在一组大括号中。一种实用的方法可能是将CHECK 重新定义为:

#define CHECK(chr, type, fn) \
    case chr: { SET(type,fn); } break;

【讨论】:

  • 啊哈!每天学些新东西。解决了它;将在 8 分钟内接受。
  • 不需要0,一个简单的; 也可以。
猜你喜欢
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多