bug with initialisation of global variables in a library (C++, gcc 2.95.2)

Fergus Henderson fjh@cs.mu.oz.au
Thu Apr 26 10:03:00 GMT 2001


On 26-Apr-2001, Kris Thielemans <kris.thielemans@ic.ac.uk> wrote:
> I have a global variable in a stand-alone .cpp file (the variable is static
> but doesn't need to be to reproduce the bug). Initialisation of this
> variable should occur by calling a constructor. (This should happen before
> the main function is started).
> 
> However, this works only when I link with the corresponding .o file. If I
> put the .o file in a library first (using ar), the constructors are NOT
> called anymore.

That's because the .o file is not being linked into your program.

If you put an object file in a (static) library, and link to the
library, then that object file will only be linked into your program if
it is referenced.  This is a feature, not a bug ;-)
If, as in your example, the object file only defines symbols with
internal linkage (e.g. global variables declared `static'), then there
is no way that it can be referenced.

One way to avoid this problem is to use shared libraries rather
than static libraries.

-- 
Fergus Henderson <fjh@cs.mu.oz.au>  |  "I have always known that the pursuit
                                    |  of excellence is a lethal habit"
WWW: < http://www.cs.mu.oz.au/~fjh >  |     -- the last words of T. S. Garp.



More information about the Gcc mailing list