Concatenate multiple tokens for X macro

北慕城南 提交于 2019-12-11 06:18:11

问题


I'm trying to use X macros and preprocessor concatenation, both for the first time, together.

I've read a lot of the other questions on SO related to preprocessor concatenation but not yet been able to wrap my head around them or how to adapt those to my use case.

The list of items is a list of ID numbers for a bunch of structs, like so:

#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)

I can declare the structs like so:

#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

Now I would also like to initialise one of the members of each struct to be equal to the ID number, such that foo_n.id = n;. I have been able to achieve the first token concatenation, by using the following:

#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)

But I have not been able to understand how to correctly expand the idea further so that the assigned value is also replaced. I have tried:

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

And various attempts at using double indirection for the concatenation. But have not been successful. The above attempt resulting in errors like the following for each item in the 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 

How can I best achieve the form foo_n.id = n?


回答1:


As far as I can tell, that should simply be :

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


来源:https://stackoverflow.com/questions/38501401/concatenate-multiple-tokens-for-x-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!