c++ static object not created

Andrew Haley aph@redhat.com
Thu Nov 20 11:58:00 GMT 2008


Kövesdi György wrote:
>> Can you give us an example of this not working?  It really should work,
>> and it works for me.
> Your example is really works.
> I checked the difference in my case, and found that the problematic object is 
> put in an archive file:
> 
> ---------- x.cpp: -----------
> #include <iostream>
> using namespace std;
> class SomeClass
> {
> public:
>   SomeClass()
>   {
>     cout << "Hello!\n";
>   }
> };
> static SomeClass my_instance;
> ------------- main.cpp: ------------
> int main()
> {
> }
> -----------------------------------------
> What i did:
> g++ main.cpp -c -o main.o
> g++ x.cpp -c -o x.o
> ar r x.a x.o
> g++ -o good main.o x.o
> g++ -o bad main.o x.a
> 
> Try to start 'bad' and 'good' executables: the 'bad' does not execute the 
> constructor. Is there any difference in linking or I created the archive 
> wrong way?

It's doing what it's supposed to do.  When you link against a static
library, an objects is only pulled into the executable if there's a
reference to it.  There is no reason to include x.o in the executable:
nothing uses it.

Andrew.



More information about the Gcc-help mailing list