Run Some Code Before main() Function in C or C++

Use GCC Attribute

You can run some code before running into your main() function in C/C++ program.

__attribute__((constructor)) is a GCC compiler attribute that specifies a function to be called automatically before the main function. [1]

#include <stdio.h>
void init() __attribute__((constructor)) {
	printf("This function is executed before main()");
}

int main() {
	printf("hello, this is main function.");
	return 0;
}

Advanced Usage

If you want to define your constructor function in an standalone library (e.g. *.so or *.a) and use gcc linker.

my_constructor.c

#include <stdio.h>
void init() __attribute__((constructor)) {
	printf("this function is executed befire main()");
}

Create the archive library.

$> gcc -c my_constructor.c -o my_constructor.o
$> ar rcs libmy_constructor.a my_constructor.o

Then, create your own main function.

#include <stdio.h>

int main() {
	printf("hello");
	return 0;
}

At the end, use linker to link them together.

$> gcc main.c -L. -lmy_constructor -o main

  1. https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html#:~:text=The constructor attribute causes the,exit () has been called. ↩︎