Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent linker from removing globals

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?

like image 345
Drealmer Avatar asked Apr 30 '09 10:04

Drealmer


1 Answers

To solve this in :

  • Visual studio (in the same solution) : Linker > General > Use library Dependency Inputs = yes
  • Gcc : link directly with .o files

I have not found a solution that I really like.

like image 53
Rexxar Avatar answered Oct 22 '22 02:10

Rexxar