Initialize global array of function pointers at either compile-time, or run-time before main()

后端 未结 5 987
甜味超标
甜味超标 2020-12-01 09:04

I\'m trying to initialize a global array of function pointers at compile-time, in either C or C++. Something like this:

module.h

ty         


        
5条回答
  •  余生分开走
    2020-12-01 09:26

    I was going to suggest this question is more about C, but on second thoughts, what you want is a global container of function pointers, and to register available functions into it. I believe this is called a Singleton (shudder).

    You could make myfunc_array a vector, or wrap up a C equivalent, and provide a function to push myfuncs into it. Now finally, you can create a class (again you can do this in C), that takes a myfunc and pushes it into the global array. This will all occur immediately prior to main being called. Here are some code snippets to get you thinking:

    // a header
    
    extern vector myfunc_array;
    
    struct _register_myfunc { 
        _register_myfunc(myfunc lolz0rs) {
            myfunc_array.push_back(lolz0rs);
        }
    }
    
    #define register_myfunc(lolz0rs) static _register_myfunc _unique_name(lolz0rs);
    
    // a source
    
    vector myfunc_array;
    
    // another source
    
    int16_t myfunc_1() { ... }
    register_myfunc(myfunc_1);
    
    // another source
    
    int16_t myfunc_2() { ... }
    register_myfunc(myfunc_2);
    

    Keep in mind the following:

    • You can control the order the functions are registered by manipulating your link step.
    • The initialization of your translation unit-scoped variables occurs before main is called, i.e. the registering will be completed.
    • You can generate unique names using some macro magic and __COUNTER__. There may be other sneaky ways that I don't know about. See these useful questions:
      • Unnamed parameters in C
      • Unexpected predefined macro behaviour when pasting tokens
      • How to generate random variable names in C++ using macros?

提交回复
热议问题