gpt4 book ai didi

c - 基于先前值的 X-macro 枚举

转载 作者:行者123 更新时间:2023-12-01 03:32:27 24 4
gpt4 key购买 nike

我想用 X-Macro 生成枚举。枚举必须根据以前的大小增加。

我有这个

#define LIST
VAR(one, 0x02)
VAR(two, 0x02)
VAR(tree, 0x03)

想要生成这个

enum{
one = 0x02 + 0,
two = 0x02 + one,
tree = 0x03 + two
}

但这行不通

#define VAR(NAME, SIZE) STORED_LOCATION_##NAME = SIZE + (STORED_LOCATION_##NAME-1)
enum{STORED_VARIABLES};
#undef VAR

这行得通,但我认为它可以更容易

#define LIST \
VAR(one ) STR(STORED_LOCATION )\
VAR(two ) PRE(one )\
VAR(tree ) PRE(two )\
VAR(fore ) PRE(tree )\

enum
{
one = 0x00,
two = 0x01 + one,
tree = 0x01 + two,
fore = 0x01 + tree,
};

#define STR(OFFSET) OFFSET,
#define PRE(NAME) sizeof(##NAME) + STORED_LOCATION_##NAME,
#define VAR(NAME) STORED_LOCATION_##NAME =
enum{STORED_VARIABLES};
#undef VAR
#undef PRE
#undef STR

最佳答案

一个有效的半解决方案可能是声明一个等效的虚拟打包结构,而不是使用它的字段的偏移量来获得所需的枚举值。

像那样(在 gcc 下工作):

文件“my.def”:

VAR(one, 0x02)
VAR(two, 0x02)
VAR(tree, 0x03)

声明结构和枚举:

#define VAR(NAME, SIZE) char NAME[SIZE];
typedef struct __attribute__ ((__packed__)) {
#include "my.def"
} myEnumStruct;
#undef VAR

#define VAR(NAME, SIZE) NAME = (offsetof(myEnumStruct, NAME) + sizeof(((myEnumStruct*)0)->NAME)),
typedef enum{
#include "my.def"
} myEnum;
#undef VAR

int main(int argc, char **argv) {
myEnum t;
#define VAR(NAME, SIZE) t=NAME; printf("Value of " #NAME " is %i\n", t);
#include "my.def"
#undef VAR

return EXIT_SUCCESS;
}

这给出了所需的:

Value of one is 2
Value of two is 4
Value of tree is 7


祝你好运!

关于c - 基于先前值的 X-macro 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38524206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com