Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!zaphod.mps.ohio-state.edu!swrinde!ucsd!ucbvax!pasteur!galileo.berkeley.edu!jbuck From: jbuck@galileo.berkeley.edu (Joe Buck) Newsgroups: comp.lang.c++ Subject: Re: Are global class objects special? Message-ID: <28241@pasteur.Berkeley.EDU> Date: 26 Sep 90 21:31:28 GMT References: <26729@mimsy.umd.edu> Sender: news@pasteur.Berkeley.EDU Reply-To: jbuck@galileo.berkeley.edu (Joe Buck) Lines: 58 In article <26729@mimsy.umd.edu>, wilson@brillig.cs.umd.edu writes: > Am I right that there is no way to vary a parameter to > a constructor for a class object having global scope > without recompilation? Well, since the constructor is invoked before main(), you couldn't influence its arguments by means of command-line parameters. I suppose you could use environment variables though: class RNG { public: RNG(int seed); private: ... whatever } RNG globalGenerator(atoi(getenv("SEED"))); which of course would blow up if SEED were not defined. I don't recommend this! |> Currently the seed must be hard coded since my tests show |> that the constructor is invoked before main is executed. This is a feature of the language. > For that matter, is there anything special about having a global > class object? I have code which runs properly when class objects > are declared within main, but when I move them up above main > the code crashes from within the constructor for the first object. This is probably an order-of-constructors problem. For example, if you try to do stream I/O from constructors with g++ and libg++ you'll get a crash when trying to construct a global object because the constructor will be called before cin, cout, or cerr is constructed. > Actually the code crashes after trying to free up heap space used > for constructing a char* within the constructor. > I'm just generally puzzled about execution of code before main > in invoked. Apparently, I can't count on all necessary > system initializations being performed before my constructors > are called. This is a libg++ problem, though it can bite users of cfront in some situations as well. I've worked around the problem by modifying gnulib3.c to call global constructors in reverse order (so libraries will be initialized before your code). You can also work around the problem by making sure your .o files are handed to the linker in an order that works (constructors are called in the order that the .o files are given to the linker). -- Joe Buck jbuck@galileo.berkeley.edu {uunet,ucbvax}!galileo.berkeley.edu!jbuck