Let's say I have an libA.so with GCC constructor.
My program "program" depends on libA.so, so when I run it, libA.so gets opened and its constructor is executed. Now, I also have a module, libC.so, which also depends on libA. I run dlopen("libC.so")
, which loads libC, and according to my experiments, also executes libA's constructor.
Dependencies look like this:
- libA has the constructor
- libB also has a constructor
- libC depends on libA and libB
- program depends on libA
- program links libC via dlopen()
Now, when I run the program:
- libA's constructor gets run before main() starts
- libB's constructor gets run by dlopen()
Apparently, dlopen executes constructors of libraries when they are loaded into memory. Is this specified somewhere, and how does the linker check which libs are already loaded?
(Why I'm asking: On an occassion, I got a constructor executed twice in situation under some not-fully-understood conditions. Am I right in presuming that this was totally broken and should never happen under normal situation?)