【发布时间】:2012-02-29 13:13:59
【问题描述】:
我已经定义了一些宏,使定义结构数组变得更加简单,但是我找不到一种方法来使用它们而不产生错误。以下是宏(以及一些示例结构来说明为什么可以使用宏(我填充的实际结构要复杂一些)):
struct string_holder {
const char *string;
};
struct string_array_holder {
struct string_holder *holders;
};
#define DEFINE_STRING_ARRAY_HOLDER(name, values) \
static struct string_holder name##__array[] = values; \
static struct string_array_holder name = { name##__array }
#define WRAP_STRING(string) { string }
当你用它来声明一个包含一项的数组时,它工作得很好:
DEFINE_STRING_ARRAY_HOLDER(my_string_array_holder, {
WRAP_STRING("my string")
});
但是当我使用多个项目时:
DEFINE_STRING_ARRAY_HOLDER(my_string_array_holder, {
WRAP_STRING("hello"),
WRAP_STRING("world")
});
我收到此错误:
错误:提供给类函数宏调用的参数过多
因此它将大括号中的逗号解释为参数分隔符。我遵循this question 的建议,并在有问题的论点周围加上括号:
DEFINE_STRING_ARRAY_HOLDER(my_string_array_holder, ({
WRAP_STRING("hello"),
WRAP_STRING("world")
}));
现在当我尝试编译它时,它会将({ ... }) 解释为statement expression 并抱怨:
警告:使用 GNU 语句表达式扩展
(由于将其解释为语句表达式而导致的一堆语法错误)
错误: 文件范围内不允许语句表达式
我该怎么做:
- 使用没有错误的宏(首选),或者
- 重写宏以在这些情况下工作?
【问题讨论】:
-
可变参数宏怎么样?见:stackoverflow.com/q/679979/929459
标签: c macros c99 c-preprocessor