Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing code before main()

Tags:

c

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.

like image 628
Paul Manta Avatar asked Jan 03 '12 14:01

Paul Manta


People also ask

Is it possible to execute some code before main function starts executing?

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.

What happens before main () in C?

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.

Why is main function executed first?

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.


1 Answers

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

like image 69
Dan Fego Avatar answered Sep 18 '22 14:09

Dan Fego