Append items to an array with a macro, in C

后端 未结 4 1614
广开言路
广开言路 2021-01-18 00:24

I have an array (C language) that should be initialized at compile time.

For example:

DECLARE_CMD(f1, arg);
DECLARE_CMD(f2, arg);
         


        
4条回答
  •  轮回少年
    2021-01-18 01:01

    You can actually use a single macro to set the function pointers, do the function declaration, set up enums to access the function pointer and strings to use in error messages and later you can use it in a switch().

    #define X_MACRO(OP) \
      OP(addi, int x, int y) \
      OP(divi, int x, int y) \
      OP(muli, int x, int y) \
      OP(subi, int x, int y)
    
    #define AS_FUNC_PTR(x,...) x,
    #define AS_FUNC(x,...) int x(__VA_ARGS__);
    #define AS_STRINGS(x,...) #x,
    #define AS_ENUMS(x,...) ENUM_##x,
    
    X_MACRO(AS_FUNC)
    
    typedef int (*foo_ptr_t)( int, int );
    foo_ptr_t foo[] = { X_MACRO(AS_FUNC_PTR) };
    
    char *foo_strings[] = { X_MACRO(AS_STRINGS) };
    
    enum foo_enums { X_MACRO(AS_ENUMS) };
    
    /** example switch()
    #define AS_CASE(x,...) ENUM_x : x(i,j);break;
    switch (my_foo_enum){
      X_MACRO(AS_CASE)
      default: do_error();
    }
    **/
    

提交回复
热议问题