Append items to an array with a macro, in C

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

    NOTE: in your question there are semicolons at the end of every line. This will seriously interfere with any attempt to use these macros. So it depends on where and how the DECLARE_CMD(...) lines are found, and whether you can fix the semicolon problem. If they are simply in a dedicated header file all by themselves, you can do:

    #define DECLARE_CMD(func, arg) &func,
    
    my_func_type my_funcs [] {
        #include "file_with_declare_cmd.h"
    };
    

    ...which gets turned into:

    my_func_type my_funcs [] {
        &f1,
        &f2,
    };
    

    Read The New C: X Macros for a good explanation of this.

    If you can't get rid of the semicolons, this will be processed to:

    my_func_type my_funcs [] {
        &f1,;
        &f2,;
    };
    

    ... which is obviously a syntax error, and so this won't work.

提交回复
热议问题