Contributors

Thursday, August 4, 2011

Dynamically loaded libraries


There are two types of libraries used: 1) static library (one with .a extn) and 2) shared libary (one with .so extn). The shared library can be included with the target executable in two ways, of which one way is to use libdl library functions. This is explained with an example below:

#include< stdio.h >
#include < stdlib.h >
#include < unistd.h >
#include < dlfcn.h >

/* The program uses shared library functions */
int main(int argc, char *argv[]) {
    void *dlh;
    int rc = 0;
/* Function pointer to hold the library functions */
    void (*fnstub)();
/* dlopen: opens the shared library,
RTLD_NOW: Flag instructs dlopen to resolve any symbols of the library before proceeding
RTLD_LAZY: Leaves undefined symbols if any
RTLD_GLOBAL: Informs all undefined symbols be resolved in subsequent dlopen */
    dlh = dlopen("./libmylib.so.1.0", RTLD_NOW);
    if (dlh == NULL) {
        printf("\nNot found");
    }
/* Fn ptr: 'fnstub' variable points to 'printfn' function */
    fnstub = dlsym(dlh, "printfn");
    if (!fnstub) {
        printf("\nFunc not fund: %s", dlerror());
    }
/* Call printfn function here */
    fnstub();
/* Close the object handle and terminate */
    dlclose(dlh);
    return(0);
}

How to compile:
gcc prog.c –ldl –ooutput_file
/* Include 'libdl' to compile this program */

No comments:

Post a Comment