Sunday, November 11, 2012

Dynamic loading and un-loading of shared libraries in C in Linux

This is the other way of using Dynamic libraries by loading/unloading at runtime.

Please refer to my earlier posts for more explanation/understanding

Step1: Implement the library source. Let us assume there are two files namely one.c and two.c each implementing one function as follows
$ vim one.c

#include <stdio.h>
int myadd(int a, int b)
{
        return a+b;
}

$ vim two.c

#include <stdio.h>
int mymult(int a, int b)
{
       return a*b;
}

Step2: Compile the sources to generate relocatable.

Note: ‘.so’ is the extension for dynamic libraries.

$ gcc -c -fpic one.c 
        ( to create a relocatable one.o )
$ gcc -c -fpic two.c 
       ( to create a relocatable two.o ) 
$ gcc -shared -o libmyown.so one.o two.o
        ( libmyown.so is the name of the dynamic library to be created )
         - shared flag used to create a shared library 

Step3: Create the source file to dynamically load our share-library.

here funAddPtr and funMultPtr are the function pointer for myadd and mymult

Please refer to man-pages for dlopen, dlsym, dlclose 

$ vim test.c


#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main()
{
void *module;
int (*funAddPtr)(int,int);
int (*funMultPtr)(int,int);

char *error;

printf("Example : Dynamic loading/un-loading of shared library\n");


/* Load dynamically loaded library */
module = dlopen("./libmyown.so", RTLD_LAZY);
if (!module) {
fprintf(stderr, "Couldn't open libmine.so: %s\n", dlerror());
exit(1);
}

    funAddPtr = dlsym(module, "myadd");
    if ((error = dlerror()) != NULL)  {
        fprintf (stderr, "%s\n", error);
        exit(1);
    }

printf("Sum of 3,4 = %d\n", funAddPtr(3,4));


funMultPtr = dlsym(module, "mymult");
if ((error = dlerror()) != NULL)  {
        fprintf (stderr, "%s\n", error);
        exit(1);
    }
    
    printf("Product of 3,4 = %d\n", funMultPtr(3,4));

dlclose(module);

return 0;
}

Step4: Compile the source and run

$ gcc -rdynamic -o test test.c -ldl

$./test

Example : Dynamic loading/un-loading of shared library
Sum of 3,4 = 7
Product of 3,4 = 12





No comments:

Post a Comment