Write two functions in C using GCC compiler, one of which executes before main function and other executes after the main function.
GCC specific syntaxes :
1. __attribute__((constructor)) syntax : This particular GCC syntax, when used with a function, executes the same function at the startup of the program, i.e before main() function.
2. __attribute__((destructor)) syntax : This particular GCC syntax, when used with a function, executes the same function just before the program terminates through _exit, i.e after main() function.
The way constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded, the dynamic loader program checks whether such sections exist, and if so, calls the functions referenced therein.
Few points regarding these are worth noting :
1. __attribute__((constructor)) runs when a shared library is loaded, typically during program startup.
2. __attribute__((destructor)) runs when the shared library is unloaded, typically at program exit.
3. The two parentheses are presumably to distinguish them from function calls.
4. __attribute__ is a GCC specific syntax;not a function or a macro.
Driver code :
I am called first I am in main I am called last
This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to access private/protected method outside a class in C++
- lvalues references and rvalues references in C++ with Examples
- Difference between cout and std::cout in C++
- C++ program to check whether a String is a Pangram or not
- Difference between pair in Multiset and Multimap in C++ STL
- How does Volatile qualifier of C works in Computing System
- How to use unordered_map efficiently in C++
- Header files in C/C++ with Examples
- C Programming For Beginners - A 20 Day Curriculum!
- Trigraphs in C++ with Examples
- Difference Between DART and C++
- How to fix auto keyword error in Dev-C++
- Important functions of STL Components in C++
- Tr0ll 3 Walkthrough of Check the Flag or CTF Problem