# In a kernel, what are “global constructors”?

I am a beginner developing kernels (though I have developed several Hello World programs in C and C++). I frequently see reference being made to global constructors (e.g., osdev https://wiki.osdev.org/Calling_Global_Constructors), but I have not been able to find a clear definition or in it.

Could someone please guide me to the correct definition? I know they are called before the kernel, but I am having trouble understanding why.

The kernel of which I take the example, is this: https://github.com/AlgorithMan-de/wyoos/commit/7eb9f8a1d5089cf7587e553e601c42db34dc94a2

in the linker.ld file, have this code:

  .data  :
{
start_ctors = .;
KEEP(*( .init_array ));
KEEP(*(SORT_BY_INIT_PRIORITY( .init_array.* )));
end_ctors = .;

*(.data)
}


in the kernel.c file, have this code:

typedef void (*constructor)();
extern "C" constructor start_ctors;
extern "C" constructor end_ctors;
extern "C" void callConstructors()
{
for(constructor* i = &start_ctors; i != &end_ctors; i++)
(*i)();
}

• It might be useful to add any other material you have read on the subject and wherein the term has been used. – dkaeae Dec 18 '18 at 15:04

In most OSs, there is a step where the process' memory is filled with its initial values. For C code, that is typically sufficient. However, sometimes you want to execute some code before main(), which is your official entry point. For example, in C++, you need to be able to call the constructor of all global objects before main() is invoked.
To resolve this, and any other run-time activities which must be done before main(), each system provides some way to execute a function before main. The article mentions that some treat it as a simple array of function pointers, but some compilers will obscure it and hide it.