use*_*856 1 c macros gcc struct
假设我有一些结构:
struct mything1 {
int foo;
int has_foo;
int bar;
int has_bar
};
Run Code Online (Sandbox Code Playgroud)
我想写一个宏来完成类似的事情
#define FILL(instance, field, value) \
do { \
instance.#field = value; \
instance.has_#field = 1; \
} while(0); \
Run Code Online (Sandbox Code Playgroud)
这样我就可以走了struct mything1 x; FILL(x, foo, 5);,但是当我尝试编译它时这不起作用。这有可能吗?值得推荐吗?
GCC 特定的非便携式解决方案很好。
您正在字符串化field而"field"不是通过标识符引用字段。请注意,标记串联是通过##, 而不是完成的#。一个小修复:
#define FILL(instance, field, value) \
do { \
instance.field = value; \
instance.has_##field = 1; \
} while(0)
Run Code Online (Sandbox Code Playgroud)
我还删除了后面的分号while(0)。该惯用语旨在FILL(x, foo, 5);通过使用宏后的分号来完成语句。否则,您最终会得到一个可能引发警告的尾随空语句。