In Windows there is a DllMain and DLL_PROCESS_ATTACH / DLL_PROCESS_DETACH flags, which allow to initialize / free resources after DLL is attached to a process... So how can I specify an entry point in case of OS X? As always, I can't find anything useful in Apple documentation :(
4 Answers
The Dynamic Library Programming Topics document on Apple’s Web site shows the use of
__attribute__((constructor))
and
__attribute__((destructor))
to implement initialisers and finalizers in dynamic libraries.
-
This is more complete answer, than mine. – malkia Jun 04 '11 at 17:09
I think malkia (upvoted) and Bavarious have the right answer, but since I already looked it up: One way to do this is to set your init routine. Look for the "Initialization Routine" in your Xcode build settings for your library. Prefix the function name with an underscore. I.e. if your init routine is called DllMain, enter "_DllMain".
Also, I have previously done some initialization using obj-c++ doing something like this:
class LibraryInit
{
public LibraryInit()
{
// do some init stuff here
}
} ;
static LibraryInit sLibraryInit();

- 15,922
- 4
- 48
- 73
-
-
I upvoted this, as it's more portable (though C++ specific). One thing that might not work with this approach (and certain compilers/linkers such as MSVC) is that if this ends up in a library, it might not get called. I might have old information about this, but it happened to us many times in the past (our studio). Usually we declare sLibraryInit() to be external, and in at least one place in the main project, we refer to it. – malkia Jun 04 '11 at 17:09
My main application statically links to a static library A with a function ABC and my dynamic library xyz.dylib also statically links to the same static library A which has the same function ABC.
Now when the main application Loads xyz.dylib using dlopen on runtime. The initializer gets called where i have called ABC function. This function ABC is getting called from main application's address space. This is really strange and i do not know, what is going wrong? Though it should have called ABC function from the dylib.

- 9,614
- 5
- 26
- 40