Global constructors and destructors in C++ have to be handled very carefully to meet the language specification. Constructors have to be called before the main function. Destructors have to be executed after it returns. Under ELF, this can be treated gracefully by the compiler. For example, the GNU C/C++ compiler, gcc, provides two auxiliary start up files called crtbegin.o and crtend.o, in addition to two normal auxiliary files crti.o and crtn.o. Together with the .ctors and .dtors sections described below, the C++ global constructors and destructors can be executed in the proper order with minimal run-time overhead.
__CTOR_LIST__
, which is the head of the global
constructor function pointer array. This array in crtbegin.o
only has one dummy element.
__DTOR_LIST__
, which is the head of the global
destructor function pointer array. This array in crtbegin.o
only has only one dummy element.
__do_global_dtors_aux
, which goes through
__DTOR_LIST__
from the head and calls each destructor function on the list.
__do_global_dtors_aux
. Please remember it has just a
function call without return since the .fini section in
crtbegin.o is part of the body of a function.
__CTOR_END__
, which is the label for the tail of the
global constructor function pointer array.
__DTOR_END__
, which is the label for the tail of the
global destructor function pointer array.
__do_global_ctors_aux
, which goes through
__CTOR_LIST__
from the tail and calls each constructor function on the list.
__do_global_ctors_aux
. Please remember it has just a
function call without return since the .init section in
crtend.o is part of the body of a function.
_init
in the
.init section and a function label _fini
in the
.fini section.
At compile time while generating the relocatable files,
gcc puts each global constructor
on __CTOR_LIST__
by putting a pointer to the constructor
function in the .ctors section.
It also puts each
global destructor on __DTOR_LIST__
by putting a pointer
to the destructor function in the .dtors section.
At link time, the gcc driver places crtbegin.o immediately before all the relocatable files and crtend.o immediately after all the relocatable files. In addition, crti.o was placed before crtbegin.o and crtn.o was placed after crtend.o.
While generating the executable file, the link editor, ld,
concatenates the .ctors sections and the .dtors sections
from all the relocatable files to form __CTOR_LIST__
and __DTOR_LIST__
, respectively. The .init
sections from all the relocatable files form the
_init
function and the .fini sections
form the _fini
function.
At run time, the system will execute the _init
function before the main function and execute the
_fini
function after the main function returns.