How can I generate a list via the C preprocessor (cpp)?

前端 未结 5 2122
慢半拍i
慢半拍i 2020-12-09 11:12

I would like to do something like the following:

F_BEGIN

F(f1) {some code}
F(f2) {some code}
...
F(fn) {some code}

F_END

and have it gene

5条回答
  •  伪装坚强ぢ
    2020-12-09 11:48

    If you have a C99 complying compiler, the preprocessor has variable length argument lists. P99 has a preprocessor P99_FOR that can do "code unrolling" like the one you want to achieve. To stay close to your example

    #define MYFUNC(DUMMY, FN, I) int FN(void) { return I; } 
    #define GENFUNCS(...)                                          \
    P99_FOR(, P99_NARG(__VA_ARGS__), P00_IGN, MYFUNC, __VA_ARGS__) \
    int (*function_table)(void)[] = { __VA_ARGS__ }
    
    GENFUNCS(toto, hui, gogo);
    

    would expand to the following (untested)

    int toto(void) { return 0; } 
    int hui(void) { return 1; }
    int gogo(void) { return 2; }
    int (*function_table)(void)[] = { toto, hui, gogo };
    

提交回复
热议问题