Home >Backend Development >C++ >How Do `__attribute__((constructor))` and `__attribute__((destructor))` Work in C/C ?
How __attribute__((constructor)) and __attribute__((destructor)) Work
When Does __attribute__((constructor)) Run?
This attribute runs when a shared library is loaded, typically during program startup.
Why Two Parentheses?
All GCC attributes follow this syntax, presumably to distinguish them from function calls.
Attributes' Nature
attribute is a GCC-specific syntax, not a function or a macro.
Compatibility
__attribute__((constructor)) and __attribute__((destructor)) work in both C and C .
Function Static Requirement
The functions attributed with __attribute__((constructor)) and __attribute__((destructor)) do not need to be static.
__attribute__((destructor)) Run Time
The destructor runs when the shared library is unloaded, typically at program exit.
Constructor and Destructor Mechanics
Shared object files contain special sections (.ctors and .dtors) that reference functions marked with constructor and destructor attributes. The dynamic loader calls these functions during library loading and unloading. Similar mechanisms exist in the static linker for both startup and shutdown.
The above is the detailed content of How Do `__attribute__((constructor))` and `__attribute__((destructor))` Work in C/C ?. For more information, please follow other related articles on the PHP Chinese website!