Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cornell!uw-beaver!apollo!vasta From: vasta@apollo.COM (John Vasta) Newsgroups: comp.lang.c++ Subject: Re: Help! Summary: static object construction order undefined Keywords: constructors, C++ i/o, extern Message-ID: <4443be62.1ad5a@apollo.COM> Date: 6 Jul 89 21:30:00 GMT References: <2774@ssc-vax.UUCP> Reply-To: vasta@apollo.COM (John Vasta) Organization: Apollo Computer, Chelmsford, MA Lines: 41 In article <2774@ssc-vax.UUCP> dmg@ssc-vax.UUCP (David Geary) writes: > > Here's something interesting: > [ ... ] >The file noworks.cxx: >---------------------------------------------------------------------- >#include "//ernie/user/geary/c++/include/stream.hxx" // c++ i/o > >class junk { public: junk() { cout << "Constructing Link\n"; } }; > >junk myjunk; > >main() { } >---------------------------------------------------------------------- > >When I compile and run, I get: > >$ noworks >Segmentation Fault > > Can anybody provide an explanation as to why this is happening? The cout object from the stream library must be initialized when the program starts up. So does your myjunk object. The order of execution of constructors for static objects in different modules is not defined. It looks like your object is getting attention first in this case, and its constructor is trying to use an uninitialized stream object. Although some people have found ways of determining or even controlling the execution order of static constructors/destructors, these techniques are not portable, so I'd advise you not to count on them. Making the object automatic (e.g. local to main) makes sure that all static objects are initialized first. If you need global visibility for an object which depends on other static objects being initialized, you can create the object dynamically (using new) and put a pointer to it in file scope. -- John Vasta Apollo Computer (division of Hewlett Packard) vasta@apollo.com M.S. CHA-01-LT (508) 256-6600 x6362 330 Billerica Road, Chelmsford, MA 01824 UUCP: {decwrl!decvax, mit-eddie, attunix}!apollo!vasta