This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

collect2 and C++ static objects


Hi,

A question regarding the information at
http://gcc.gnu.org/onlinedocs/gcc-4.2.2/gccint/Collect2.html#Collect2,
particularly the fact that collect2 will arrange for constructors to be
called from the start of the body of main().

What happens if the program relies on constructors being called at an
earlier point, for example when initialising one global object from
another as below ? The example has a global object "str" being
initialised to a copy of another global object "Test::str". On my
system, this code runs correctly if the two .C files are built as normal
objects and then linked into an executable but crashes if "Test.C" is
built as a shared object. With additional debug messages it is a simple
matter to show that operators/methods are called on an object that was
never constructed.

Or is the example below invalid because it relies on a particular
sequence of initialisation ?

Thanks,

Duncan.


Source 1 "a.C"
===========

#include <iostream>
#include <Test.h>

std::string str=Test::str;

int main()
{
    std::cout << "Hi, str=" << str << std::endl;
}

Source 2 "Test.h"
=============

#include <string>

using std::string;

class Test
{
public:
    const static string str;
};

Source 2 "Test.C"
==============

#include <Test.h>

const string Test::str="xxx";



holywells$ g++ -I. -L. -fPIC -c a.C -o a.o      
holywells$ g++ -I. -L. -fPIC -c Test.C -o Test.o
holywells$ g++ -I. -L. -fPIC a.o Test.o -o a.out
holywells$ ./a.out
Hi, str=xxx
holywells$ g++ -I. -L. -fPIC -shared Test.C -o Test.o
holywells$ g++ -I. -L. -fPIC a.o Test.o -o a.out     
holywells$ ./a.out                                   
Segmentation fault(coredump)
holywells$ 


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]