What are the rules for initializing a static object declared in another shared library? For example, consider the following:
X.hpp file:
struct X { X (); static X const s_x; }; struct Y { Y (X const &) {} };
X.cpp file:
#include "X.hpp" #include <iostream> X::X () { std::cout << "side effect"; } X const X::s_x;
I compiled X.cpp in the libX.a static library, and I tried to link the following executable file to it (main.cpp file):
#include "X.hpp" int main () { (void)X::s_x;
only with (1) or (2), nothing happens. But if I add (3), the static object is initialized (i.e., a "side effect" is printed). (I am using gcc 4.6.1).
Is there any way to predict what will happen here?
I do not understand how command (2) does not force the X::s_x create by default, whereas (3) does.
EDIT: build commands:
g++ -c X.cpp g++ -c main.cpp ar rcs libX.a Xo g++ -o test main.o -L. -lX
source share