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

后端 未结 5 977
甜味超标
甜味超标 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:30

    Ok I worked out a solution based on Matt Joiner's tip:

    module.h

    typedef int16_t (*myfunc_t)(void);
    extern myfunc_array[];
    
    class FunctionRegistrar {
    public:
        FunctionRegistrar(myfunc_t fn, int fn_number) {
            myfunc_array[fn_number - 1] = fn; // ensures correct ordering of functions (not that important though)
        }
    }
    

    module.cpp

    #include "module.h"
    
    myfunc_array[100]; // The size needs to be #defined by the compiler, probably
    

    func1.cpp, func2.cpp, ... funcN.cpp

    #include "module.h"
    
    static int16_t myfunc(void) { ... }
    
    static FunctionRegistrar functionRegistrar(myfunc, NUMBER);
    

    Thanks everyone!

提交回复
热议问题