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.
Executing code before main() Bookmark this question. Show activity on this post. 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.
The _start Function. For most C and C++ programs, the true entry point is not main , it's the _start function. This function initializes the program runtime and invokes the program's main function.
This is because you can create any number of functions in a program. You can have 1 function, 10, 2340 functions, or whatever. The program needs to know where to start. This is the purpose of the main function, as that is always the first function called.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With