HenryR
HenryR

Reputation: 8519

C++: link library twice, are global constructors run twice?

If I have a library foo that has some static initialization code in it, and a linking situation as follows:

 executable -> libShared.so (dynamic linking)
 executable -> libFoo.a (static linking)
 libShared.so -> libFoo.a (static linking)

Does this result in the static initialization code being run twice - and if it has side-effects, possibly doing two different visible things?

libShared.so has done the right thing by only exporting its own symbols, and not exporting any of libFoo.a. But there are two copies of libFoo.a in the process, effectively namespaced away from one another. Is my understanding right - there'll be a duplicate initialization step?

(Naturally the right approach is to have libFoo.a not do anything like create visible side-effects in its static initializers, but let's assume that ship has sailed...).

Upvotes: 3

Views: 630

Answers (2)

MSalters
MSalters

Reputation: 179877

Yes, the constructors will be run twice. When you build an executable or shared library, a helper method is created which enumerates all globals to be constructed and calls their initializers (other methods are allowed by ISO C++, but not used for systems with shared libraries). These helpers are called when the executable and shared library are loaded.

Now you happen to have two such methods initializing two distinct parts of memory. That creates two objects, and their addresses will differ.

This would have been different if the executable only had an extern declaration of the global, but obviously it can't - it uses the same static library.

PS. Destructors for global object have their own helper method, working roughly the same.

Upvotes: 3

user2100815
user2100815

Reputation:

Static libraries are simply concatenations of object files - there is no code in them to run the constructors of static objects, unless you explicitly provide such code. So static objects in a static library will not have constructors be run twice, or possibly even once. Also, because of the way that static libraries are searched by most linkers, it is a very common practice to link to them multiple times.

Upvotes: 0

Related Questions