next up previous
Next: Dynamic Linking and Up: The .init and Previous: The .init and

Global Constructors and Destructors in C++

 

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.

.ctors

This section holds an array of the global constructor function pointers of a program.

.dtors

This section holds an array of the global destructor function pointers of a program.

crtbegin.o

There are four sections:

crtend.o

There are also four sections:

crti.o

It has only a function label _init in the .init section and a function label _fini in the .fini section.

crtn.o

It has only a return instruction each in the .init and .fini sections.

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.



next up previous
Next: Dynamic Linking and Up: The .init and Previous: The .init and



J.H.M.Dassen
Tue Aug 1 14:18:10 MDT 1995