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

前端 未结 5 2123
慢半拍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:47

    There's this thing called X Macro which is used as:

    a technique for reliable maintenance of parallel lists, of code or data, whose corresponding items must appear in the same order

    This is how it works:

        #include 
    
    //you create macro that contains your values and place them in (yet) not defined macro
    #define COLORS\
        X(red, 91)\
        X(green, 92)\
        X(blue, 94)\
    
    //you can name that macro however you like but conventional way is just an "X"
    
    //and then you will be able to define a format for your values in that macro
    #define X(name, value) name = value,
    typedef enum { COLORS } Color;
    #undef X //just another convention (so you don't use it accidentally, I think)
    
    int main(void)
    {
        #define X(name, value) printf("%d, ", name);
        COLORS
        #undef X
        return 0;
    }
    

    Solution for your problem would be:

    #define FUNCTIONS \
    F(f1, code1)\
    F(f2, code2)\
    F(f3, code3)
    
    #define F(name, code) int name(void){code}
    FUNCTIONS
    #undef F
    
    
    #define F(name, code) &name,
    int (*function_table[])(void) = { FUNCTIONS };
    #undef F
    

提交回复
热议问题