为什么此嵌套宏替换失败? [英] Why is this nested macro replacement failing?
问题描述
我正在尝试使用 X宏概念,以便可以将所有结构成员初始化为自定义默认值(无效).我编写以下代码:
I am trying to apply the X Macro concept, in order to have the possibility to initialize all struct members to a custom default (invalid) value. I write the following code:
#define LIST_OF_STRUCT_MEMBERS_foo \
X(a) \
X(b) \
X(c)
#define X(name) int name;
struct foo {
LIST_OF_STRUCT_MEMBERS_foo
};
#undef X
#define X(name) -1,
static inline void foo_invalidate(struct foo* in) {
*in = (struct foo){
LIST_OF_STRUCT_MEMBERS_foo
};
}
#undef X
#define X(name) -1,
#define foo_DEFAULT_VALUE { LIST_OF_STRUCT_MEMBERS_foo }
#undef X
static struct foo test = foo_DEFAULT_VALUE;
但是,当我运行预处理程序时,foo_DEFAULT_VALUE
的定义无法将X(name)
调用替换为-1,
However, when I run the preprocessor, the definition of foo_DEFAULT_VALUE
fails to substitute the X(name)
calls with -1,
预处理器输出:
struct foo {
int a; int b; int c;
};
static inline void foo_invalidate(struct foo* in) {
*in = (struct foo){
-1, -1, -1, /*Here the substitution worked nicely*/
};
}
static struct foo test = { X(a) X(b) X(c) }; /*Why this substitution failed?*/
我认为 C宏可以引用其他宏.你知道为什么替换失败吗?有什么解决方法吗?
I thought C-macros could refer to other macros. Do you know why that substitution fails? Is there any workaround?
我可以忍受foo_invalidate
,但是我不愿意放弃在初始化时直接使用值的步骤.
I could live with foo_invalidate
, but I am reluctant to give up one step from having a value to be used directly at initialization.
推荐答案
让我们假装我们是预处理器并遇到了以下问题:
Let's pretend that we are the preprocessor and encountering the line:
static struct foo test = foo_DEFAULT_VALUE;
通过1:
static struct foo test = { LIST_OF_STRUCT_MEMBERS_foo };
第2遍:
static struct foo test = { X(a) X(b) X(c) };
第3步:在此行中,没有任何要扩展的内容,因为X
未定义.
Pass 3: Nothing to expand as X
is undefined on this line.
一种解决方法是定义一个const变量(可能但不一定是static
)用作默认值:
One workaround could be defining a const variable (possibly but not necessarily static
) to be used as default value:
#define X(name) -1,
static const struct foo foo_DEFAULT_VALUE = { LIST_OF_STRUCT_MEMBERS_foo };
#undef X
哪个生成:
static const struct foo foo_DEFAULT_VALUE = { -1, -1, -1, };
这篇关于为什么此嵌套宏替换失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!