collect2 and C++ static objects

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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 of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux