Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
attribute((constructor)) and attribute((destructor)) syntaxes in C in tutorials point ?
Here we will see how to write a code where two functions are present, and one function will be executed before the main function, and another function will be executed after main function. These features are used to do some startup task before executing main, and some clean up task after executing main.
To do this task we have to put attribute for these two functions. When the attribute is constructor attribute, then it will be executed before main(), and when the attribute is destructor type, then it will be executed after main().
We are using GCC functions. The function is __attribute__(). In this case we are using two different options. The Constructor and the Destructor with the __attribute__() function.
Syntax
// Constructor syntax return_type function_name() __attribute__((constructor)); // Destructor syntax return_type function_name() __attribute__((destructor));
The syntax __attribute__((constructor)) is used to execute a function when the program starts, and the syntax __attribute__((destructor)) is used to execute the function when main() function is completed.
Example
Here is a complete example demonstrating constructor and destructor attributes −
#include <stdio.h>
void before_main() __attribute__((constructor));
void after_main() __attribute__((destructor));
void before_main() {
printf("This is executed before main.<br>");
}
void after_main() {
printf("This is executed after main.<br>");
}
int main() {
printf("Inside main<br>");
return 0;
}
This is executed before main. Inside main This is executed after main.
Key Points
- Constructor functions run before main() starts execution
- Destructor functions run after main() completes execution
- These attributes are GCC-specific extensions, not part of standard C
- Multiple constructor/destructor functions can be defined with priority levels
Conclusion
The __attribute__((constructor)) and __attribute__((destructor)) provide a way to execute initialization and cleanup code automatically. These GCC extensions are useful for library initialization and resource management tasks.
