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
Since you allow C++, the answer is obviously yes, with templates:
template int16_t myfunc() { /* N is a const int here */ }
myfunc_array[] = { myfunc<0>, myfunc<1>, myfunc<2> }
Now, you might wonder if you can create that variable-length initializer list with some macro. The answer is yes, but the macro's needed are ugly. So I'n not going to write them here, but point you to Boost::Preprocessor
However, do you really need such an array? Do you really need the name myfunc_array[0]
for myfunc<0>
? Even if you need a runtime argument (myfunc_array[i]
) there are other tricks:
inline template int16_t myfunc_wrapper(int i) {
assert (i : myfunc_wrapper(i-1);
}
inline int16_t myfunc_wrapper(int i) {
return myfunc_wrapper(i); // NUMBER is defined on with g++ -DNUMBER=N
}