Issue
I've been reading a book detailing the C/C++ build process, and it mentions that there's a GNU extension that allows you to specify a function to be run before main() is started.
What would be some good use cases for such a function? What's the difference with just doing it first thing when main() starts? I am more after theoretical answers rather than any specific code.
Solution
The extension you describe is not for normal use.
As you correctly say, there's no difference between calling the routines at the beginning of your program, or at the beginning of your program (except when you want to go before some standard initialization is done) This means that in case of some libraries, that require other libraries not to be initialized before, you need to run your initialization code out of main()
, when the C runtime is being initialized. The feature you describe is not GNU specific, but is included in the ELF binary format. ELF provides for a loaded module to include two entry points init
and fini
, to be called first on loading, and to be called last, before unloading. Also, there's another entry point (normally called _start
, but this can be changed by the linker) as the entry point to the program, which is normally reserved to the c runtime module, that ends calling main()
.
Some libraries provide a init
function to be called on library loading, to avoid to force the user to call some initialization routine himself, and ensure that you will always get a properly initialized library anyway. Rememember that this feature is not done at program loading, but at library loading, but ELF sees a program as a library with just a single entry point. The linker/loader normally selects the different init
routines to be called in an order that allows the library dependencies to be properly initialized (a library A that depends on B, makes B's init
routine to be called before A's init
)
Answered By - Luis Colorado Answer Checked By - David Marino (WPSolving Volunteer)