Ctor init does not call global ctor instances in the library

I am developing an application and library using SourceryGpp lite for the hand.

I do not use standard libs files or default startup files. Therefore, to call global ctrs, I do the following code:

ldr r0,=__ctors_init__ ldr r0,[r0] mov lr,pc bx r0 

So, the problem is that I define some global instances in the static library, but their ctors are never called by the code above. It is strange that global ctors applications are successfully called, does anyone know why?

+1
source share
2 answers

This is a well-known issue with static libraries and global variables with runtime initialization.

Most linkers will only include the components of the static library needed to run the dependency on the main program. If none of the objects in the compilation unit are used, the linker deletes never adds the compilation unit as a whole, and side effects of global initialization do not occur.

There is a good explanation here (summary summary here )

You would have the same problem with the standard static code provided by the library.

+5
source

The standard explicitly allows you to delay the initialization of static objects (C ++ 98, [basic.start.init]):

It is determined by the implementation whether the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of the object namespace scope is executed before the first main statement. If initialization is delayed to some point in time after the first statement of main, this should happen before the first use of any function or object defined in the same translation unit as the object to be initialized.

(The latest C ++ 0x project has a slightly different wording.)

So, if you do not use any translation unit at all, all objects defined there can be completely deleted.

+3
source

All Articles