Thursday, April 2, 2015

creating a GCC shared library in linux and accessing the shared library in C/C++

A library is a file containing compiled code from various object files stuffed into a single file.  A library can be of two types:

1.     Shared Library
2.     Static library

1.   Shared Library:


Shared Libraries are the libraries that can be linked to any program at run-time. They provide a means to use code that can be loaded anywhere in the memory. Once loaded, the shared library code can be used by any number of programs.

 2.   Shared Library Names:


Every shared library has a special name called the “soname”. The soname has the prefix “lib”, the name of the library, the phrase “so'', followed by a period and a version number that is incremented whenever the interface changes .

Eg libtest.so, libtest.so.1.1

3.   Placement in File System:

There are mainly three standard locations in the filesystem where a library can be placed.

·      /lib
·      /usr/lib
·      /usr/local/lib

we can even use the non standatd library location. In that case the path should be added to the LD_LIBRARY_PATH

1.   How to create the Shared library with GCC  in linux


Step 1:Let us suppose a simple code  shared.c
int a(int b)
{
  return b+1;
}

int c(int d)
{
  return a(d)+1;
}




Step2:  compile our library source code in to position independent code(PIC)

          gcc –c  -Wall –Werror –fpic  shared.c

       Here libtest.so is the name of the shared library



Step 3: create a shared library from object file

     gcc  -shared –o libtest.so  shared.o

Step 4: making the library available at runtime using LD_LIBRARY PATH

     export LD_LIBRARY_PATH=/home/username:$LD_LIBRARY_PATH

Here /home/username is the sample path to the shared library. This should be
different as per the location of the shared library

Step 4:  create a  file that uses the shared library name test.c

     
#include 
#include 
#include 

typedef int (*pointer)(int b);


int main()
{
int b,d;
void *lib;
 pointer calc;
  lib=dlopen("libtest.so",RTLD_LAZY);
   if (!lib)
 {
  printf("failed to open libtest.so: %s \n", dlerror());
  exit(1);
 }


  calc= (pointer) dlsym(lib,"a");
  b= calc(2);
  calc= (pointer) dlsym(lib,"c");
  d= calc(2);

  dlclose(lib);


  printf("b is %d d is %d\n",b,d);
  return 0;
}

Here  the above program uses the <dlfcn.h> library to open the shared library  libtest.so , locate the symbol and call the function from shared library.

dlopen() function opens the shared library and dlsym() looks up a symbol in a shared library.

No comments:

Post a Comment