连接X宏的多个标记

我正在尝试第一次使用X宏和预处理器连接。

我已经阅读了很多关于预处理器连接的SO的其他问题,但还没有能够解决它们或者如何使这些问题适应我的用例。

项目列表是一组structs的ID号列表,如下所示:

 #define LIST_OF_ID_NUMS \ X(1) \ X(2) \ X(3) \ X(4) \ X(5) \ X(6) \ X(7) \ X(8) \ X(9) \ X(10) \ X(11) 

我可以像这样声明结构:

 #define X(id_num) static myFooStruct foo_## id_num ; LIST_OF_ID_NUMS #undef X // gives: 'struct myFooStruct foo_n;' where 'n' is an ID number 

现在我还要初始化每个结构的一个成员等于ID号,这样foo_n.id = n; 。 通过使用以下内容,我已经能够实现第一个令牌连接:

 #define X(id_num) foo_## id_num .id = 3 ; LIST_OF_ID_NUMS #undef X // gives: 'foo_n.id = x' where 'x' is some constant (3 in this case) 

但我无法理解如何进一步正确地扩展这个想法,以便更换指定的值。 我试过了:

 #define X(id_num) foo_## id_num .id = ## id_num ; LIST_OF_ID_NUMS #undef X // Does NOT give: 'foo_n.id = n;' :( 

以及使用双重间接进行连接的各种尝试。 但没有成功。 上述尝试导致LIST_OF_ID_NUMS每个项目的错误如下:

 foo.c:47:40: error: pasting "=" and "1" does not give a valid preprocessing token #define X(id_num) foo_## id_num .id = ## id_num ; ^ foo.c:10:5: note: in expansion of macro 'X' X(1) \ ^ foo.c:48:2: note: in expansion of macro 'LIST_OF_ID_NUMS ' LIST_OF_ID_NUMS 

我怎样才能最好地实现foo_n.id = n的forms?

据我所知,这应该只是:

 #define X(id_num) foo_## id_num .id = id_num ;