Executing code before main()

You can do it with __attribute__ ((constructor)). I've tested the following example with both gcc and clang. That being said, it's not part of the language.

#include <stdio.h>

void __attribute__ ((constructor)) premain()
{
    printf("premain()\n");
}

int main(int argc, char *argv[])
{
    printf("main()\n");
    return 0;
}

It does the following:

$ ./test
premain()
main()

GCC documents it at: https://gcc.gnu.org/onlinedocs/gcc-8.3.0/gcc/Common-Function-Attributes.html#Common-Function-Attributes


With gcc, you can do so by using the constructor function attribute, e.g.

__attribute__ ((__constructor__)) 
void foo(void) {
        ...
}

This will invoke foo before main.

Note: This is probably not portable to other compilers.


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 calling main(), the OS calls another function called start-up module 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 calling main().

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.

Tags:

C