I want to add hook function, which will be called when shared library is unloaded. Library is linked on complitaion. Is it possible to do such thing? Maybe gcc has flag for it?
I saw similar solution for loading library on runtime, but it doesn't meet my expectations.
For Linux systems, the dlopen()/dlclose() man page explains how to add such a function to your library:
Initialization and finalization functions
Shared objects may export functions using the
__attribute__((constructor))and__attribute__((destructor))function attributes. Constructor functions are executed beforedlopen()returns, and destructor functions are executed beforedlclose()returns. A shared object may export multiple constructors and destructors, and priorities can be associated with each function to determine the order in which they are executed. See the gcc info pages (under "Function attributes") for further information.An older method of (partially) achieving the same result is via the use of two special symbols recognized by the linker:
_initand_fini. If a dynamically loaded shared object exports a routine named_init(), then that code is executed after loading a shared object, beforedlopen()returns. If the shared object exports a routine named_fini(), then that routine is called just before the object is unloaded. In this case, one must avoid linking against the system startup files, which contain default versions of these files; this can be done by using the gcc(1)-nostartfilescommand-line option.Use of
_initand_finiis now deprecated in favor of the aforementioned constructors and destructors, which among other advantages, permit multiple initialization and finalization functions to be defined.
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