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

Kris Thielemans kris.thielemans@ic.ac.uk
Thu Apr 26 07:08:00 GMT 2001


Hi,

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.

Attached are 2 .cpp files and a Makefile to reproduce the problem. The
easiest way to do this is by typing:
	make -f Makefile.globalvarinit run

This will compile the .o files, make the library and link in 2 ways:
	g++ -o globalvarinitnolib globalvarinitmain.o globalvarinit.o
	g++ -o globalvarinitlib globalvarinitmain.o globalvarinit.a
And then run the 2 executables. You probably will see the following output

no lib version
./globalvarinitnolib
Executing default constructor
executing 'int' constructor with value 4
In main program
lib version
./globalvarinitlib
In main program

That is, the 'lib' version does not execute the constructors.

Test systems:
SuSE Linux with gcc 2.95.2
Solaris with gcc 2.95.2
cygwin on NT with gcc 2.95.3-3


Note that the obvious work-around to keep it out of the library does not
really work in my actual program, because the constructor needs things from
the library, and the library needs the global variables, so I get unresolved
linking errors.

Can anyone help? Is this a known bug?


Kris Thielemans
(kris.thielemans@ic.ac.uk)
Imaging Research Solutions Ltd
Cyclotron Building
Hammersmith Hospital
Du Cane Road
London W12 ONN, United Kingdom

Phone on :   +44 (020)8383 3731
FAX on :     +44 (020)8383 2029

web site address:
http://www.irsl.org/~kris
-------------- next part --------------
A non-text attachment was scrubbed...
Name: globalvarinit.cpp
Type: text/x-c++
Size: 256 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc/attachments/20010426/09bb5759/attachment.bin>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: globalvarinitmain.cpp
Type: text/x-c
Size: 85 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc/attachments/20010426/09bb5759/attachment-0001.bin>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Makefile.globalvarinit
Type: text/x-makefile
Size: 485 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc/attachments/20010426/09bb5759/attachment-0002.bin>


More information about the Gcc mailing list