I am using static global variables constructors as a trick to conveniently register functions, the idea goes something like this:
typedef int (*FuncPtr)(int);
struct RegHelper
{
RegHelper(const char * Name, FuncPtr Func)
{
Register(Name, Func);
}
}
#define REGISTER(func) RegHelper gRegHelper_ ## func (#func, func);
Now I can register functions this way (I use it to implement some kind of reflection):
int Foo(int a)
{
return a * 123;
}
REGISTER(Foo)
int Bar(int a)
{
return a * 456;
}
REGISTER(Bar)
The problem is that if I use this in a static library, sometimes the linker detects that the compilation unit is not used, and it drops the whole thing. So the global variables are not constructed, and the functions are not registered...
My question is: What can I do to work around this? Calling dummy functions in each compilation unit during initialization seems to trigger the construction of the global variables, but that doesn't feel very safe. Any other suggestion?