Append items to an array with a macro, in C

后端 未结 4 1628
广开言路
广开言路 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

    Yes, it is possible. The usual trick is to have all the DECLARE_CMD(func, args) lines in one (or more) include files, and to include those in various places with an appropriate definition for the macro.

    For example:

    In file 'commands.inc':

    DECLARE_CMD(f1, args)
    DECLARE_CMD(f2, args)
    

    In some source file:

    /* function declarations */
    #define DECLARE_CMD(func, args) my_func_type func;
    #include "commands.inc"
    #undef DECLARE_CMD
    
    /* array with poiners */
    #define DECLARE_CMD(func, args) &func,
    my_func_type* my_funcs[] = {
        #include "commands.inc"
        NULL
    };
    

提交回复
热议问题