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 = .;


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++)
  • $\begingroup$ It might be useful to add any other material you have read on the subject and wherein the term has been used. $\endgroup$ – dkaeae Dec 18 '18 at 15:04

The link you provided has a clear definition:

This tutorial discusses how to correctly invoke global constructors, such as those on global C++ objects. These are supposed to have run before your main function, which is why the program entry point is normally a function called _start.

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.

The key takeaway is that these are handled before the entry point of your program.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.