Take the tour ×

I have the following problem: My (C++-)project consists of several subprojects. In each, I have several files with code I want to run at startup. My solution so far is to use static variables which call the respective code on initialization like this:

// Foo.cpp

static TFooRegistry sFooRegistry;   // does stuff in constructor.

When building my project using dlls for each subproject, everything works fine and the code runs as expected. When linking the subprojects statically, however, the linker determines that Foo.o contains no code ever referenced from outside and optimizes it away. Of course I could add a reference to sFooRegistry somewhere else, but this is tedious and error prone.

What (standard conformant) ways of solving this are there?

OK, what can I do on mac/gcc and win/visual studio?

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

There are no standard conformant ways of forcing objects in libraries to be initialised - you have to use tricks depending on your particular platform(s). The difference between a DLL and and a static library (on Windows, at least) is that the former has start-up and shut-down code that is executed by the OS, whereas the latter is just a concatenation of object files.

Also, the linker is not optimising away your start up code - it is simply not linking it, because it apparently is never used. Linkers are pretty stupid beasts - if you want to find out how they do what they do, take a look at the book Linkers & Loaders.

share|improve this answer
Doh! Dear Bjarne: Why? –  Tobias Aug 19 '09 at 15:44
What's the difference between a linker optimizing code away and not linking it? I thought this was just two names for the same thing. –  Tobias Aug 19 '09 at 15:48
C++ was designed to work with existing linkers (see Stroustrup's D&E book) which had/have no concept of constructors. –  anon Aug 19 '09 at 15:48
Well, you can do the same in C: int sRegisterFoo() {...}; static int sFooRegistry = sRegisterFoo(); –  Tobias Aug 19 '09 at 15:53
There is no guarantee that will get linked either. –  anon Aug 19 '09 at 15:57
show 3 more comments

Some trick, but review it. For Win system (but not linux) use explicit dllexport - in this case linker doen't knows if this symbol used by outer app or not.

share|improve this answer
add comment

Your Answer


