[gnu.g++.help] g++1.37.0 on an Encore Multimax running Mach 1.0

jj00@eurotherm.co.uk (John Juer) (06/05/91)

I'm not a g++ or gnu expert but there are so many messages about this
that this explanation may be helpful. I do not guarantee that it is
correct.

ld++ as well as linking your C++ programs will cause code to call
constructors and destructors of global C++ objects to be linked in.

collect provides a way of doing the latter if you cannot use the gnu
linker i.e if you have COFF, extended COFF etc.

The wonderful (and free which makes it even more wonderful! :-) g++
compiler generates special routines for modules that contain static
C++ objects. These are put into each module and have well known names
that start with things like GLOBAL_.I or something similar depending
on which machine you are one. They call the appropriate constructor
and destructor for the static object.

collect (and I guess ld++) looks at your object files and figures out
from the names within what static C++ objects you have and hence what
constructors and destructors have to be called before main and after
exit. It then generates two lists in assembler __CTOR_LIST__ for the
constructors and __DTOR_LIST__ which contain pointers to the relevant
routines described in the previous paragraph. g++ also calls a routine
called __main right after entry into main, and this walks the CTOR list
calling the constructor routines. Here is a version (which is not
guaranteed to work on your machine - it does on mine). (It should be
compiled by a C compiler!)

void
__do_global_init ()
{
  extern void (*__CTOR_LIST__)();
  register void (**ppf)() = &__CTOR_LIST__;
  register int *pi = (int *)ppf;
  register int nc = *pi; 
  ppf++;

  while (nc)
    {
      (*ppf)();
      nc--;
      ppf++;
    }
}

__main() {
__do_global_init();
}

A similar routine is called at exit to destruct your static C++
objects.

So having run collect on your object files you can use a standard
linker and link in the calls to construct and destruct your static C++
objects.

I hope this helps.

Janet:    jj00@uk.co.eurotherm    | Eurotherm Limited, Faraday Close,
Internet: jj00@eurotherm.co.uk    | Durrington, Worthing, W.Sussex, England.
UUCP:     {ukc,uunet}!etherm!jj00 | Phone: +44 903 68500 x2229 Fax: +44 903 65982