Is it possible to create a function in a shared library (.dll on Windows, and .so on linux) that is executed right when the library is loaded (or unloaded)?
Just like the main() function is the entry point for an executable, can I define a function to execute when the DLL is loaded, or unloaded?
E.g.:
void _atstart()
{
// Initialize some stuff needed by the library
}
void _atexit()
{
// Release some allocated resources
}
I think I’ve seen such an example somewhere, but I couldn’t find it any more, and couldn’t find anything on the internet about this.
If it is of any use, I’m compiling the code with MinGW.
For windows you can use
DllMain:The second parameter
fdwReasonspecifies if the library is loaded or unloaded. Full reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspxFor Linux you might be able to use:
but this only came up after a google search, so you have to investigate by yourself – http://tdistler.com/2007/10/05/implementing-dllmain-in-a-linux-shared-library