Go to Google Groups Home    comp.lang.c++.moderated
Re: Rules concerning static initialisation

Nick Hounsome <nick.houns...@googlemail.com>

On 3 July, 02:49, matt <mattjb...@ntlworld.com> wrote:

> What are the rules concerning static initialisation of intrinsic
> types?

> I have read example code of the form

> namespace
> {
>     bool register()
>     {
>        // blah - do something useful in here
>     }

>     bool registered = register();

> }

> used to ensure that something is done at program startup and have
> played with it a bit.  If I attempt to move this and associated code
> into a library and link to it it does not get called.  What are the
> rules concerning initialiation of types and where can I find em?

The "intrinsic types" part is misleading here.
There are two issues:

Firstly, unlike initialisation with a constant which is done at
compile time, this requires runtime initialisation in code before main
().

The second issue is to do with libraries and the C++ standard does not
deal with libraries or linking (at least beyond the level of
'compilation unit').
In practice, linkers only pull in object files from libraries to
satisfy references to symbols from already linked code. Since there is
no reference to anything in the compilation unit including the example
code the linker sees no need to include it and hence no need to
include code to do the initialisation.
To get around this you must include the .o file directly in the link
command rather than via a library (unless your linker has an option to
force linking of the entire library)

--
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]