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

Leave a Comment