In object-oriented languages (C++) you can execute code before main() by using a global object or a class static object and have their constructors run the code you want.
Is there any way to do this in C? I don’t have any specific problem I’m trying to solve, I’m just curious. One thing this might be useful for is automatically initializing a library.
There are ways using
__attribute__but those are very specific to your compiler and code that is written using these are not really portable. On the other hand, the C language does not provide any start-up modules/libraries.In C, logically
main()is the first function called by the OS. But before callingmain(), the OS calls another function calledstart-upmodule to setup various environment variables, initialize (un-initialized) static variables, build a stack frame (activation record) and initialize the stack pointer to the start of the stack area and other tasks that have to be done before callingmain().Say if you are writing code for embedded systems where there is no-or-minimal OS to do the above mentioned work, then you should explore these options which are compiler dependent. Other than GCC, Turbo-C and Microsoft C compilers provides facilities to add code in a particular hardware machine (f.e. 8086 machines).
In other words, the start-up modules are not meant for the programmers.