In a previous article I explained how to create a shared library (in Mac OS X) and how to build an application using this shared library.
Instead of linking the application against the library, the developer can choose to manually load the shared library.
This procedure is good enough if the developer wants to control the linking of the library himself. To do this job you have to use the "dl" interface. So, the developer first needs to open a handle to that library, and then he needs to retrieve function pointers from the shared library.
Starting from the source code of the previous article, we are going to modify only the main program and then we are going to compile it
The main.c becomes the following one:
#include "helloworld.h"
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
void *lib_handle;
int (*hello_func)();
lib_handle = dlopen("libhello.dylib",RTLD_NOW);
if(lib_handle==NULL) {
/* Manage errors */
}
hello_func = (int (*)()) dlsym(lib_handle,"printHelloWorld");
if(hello_func==NULL) {
/* Manage errors */
}
(*hello_func)();
exit(EXIT_SUCCESS);
}