Total Pageviews

Tuesday, December 9, 2014

Using Shared Libraries

I after viewing a webinar on shared libraries, I thought I would post the examples. Many times we are asked to build software and we don't know what goes where. Hopefully this will help clear things up. I will use two small 'c' programs to demonstrate the idea. First the program that will be used to build the library displayuid.c: 

/* This will be so file displayuid.c */
#include 
#include 
void display_uid () {
  int real = getuid();
  int euid = geteuid();
  printf("The REAL UID =: %d\n", real);
  printf("The EFEECTIVE UID =: %d\n", euid);
} 
Next the main program itself, standard.c: 
/* This will be so the main program standard.c  */
#include 
int main () {
  printf("This is from the main program\n");
  display_uid();
  return 0;
}  
First compile the program that is to be used as a library: 
$ gcc -c -fPIC displayuid.c
The program is compiled with 'PIC' to make it relocatable. The resulting output will be a '.o' file:
displayuid.o
Next create the actual shared library:
gcc -shared -o libdisplayuid.so displayuid.o 
libdisplayuid.so will be the name of the new shared library, 
displayuid.o is the name of the object file that was created earlier.
Now as root place the shared library in a location available system 
wide:
# mkdir /usr/local/lib/tup
# cp libdisplayuid.so /usr/local/lib/tup
# chmod -R 755 /usr/local/lib/tup
Continuing as root, make the library known system wide: 
# echo "/usr/local/lib/tup" > /etc/ld.so.conf.d/tup.conf
# ldconfig
(rebuilds the cache)
# ldconfig -p |grep libdisplay
(checks that it is there) 
Now compile the test program: 
$ gcc -L/usr/local/lib/tup standard.c \
-o standard -ldisplayuid
Finally run the program:
./standard 
ldd standard