Skip to main content
CentOSRaspberry PiUbuntu

Understanding Shared Libraries in Linux

By April 6, 2014September 12th, 2022No Comments

From an administrative perspective I think  it can sometimes be difficult to understand shared libraries especially if you have never created one. By creating shared libraries from scratch along with a least one program that makes use of the program then will be useful to understanding how they work and how we administer them.

We will start by looking at two C source files; one that will make up the library file and one that will be the client program that references a function from the library.

lib

Library Module

/*     this will be the library module
    theurbanpenguin.com*/
void display_uid () {
    int real = getuid();
    int euid = geteuid();
    printf("The REAL UID =: %dn", real);
    printf("The EFFECTIVE UID =: %dn", euid);
}

Main program

/*     this is the calling program that uses library
 *     theurbanpenguin.com
 * */
#include <stdio.h>
#include <unistd.h>
int main () {    
    printf("This is the Main Programn");
    display_uid();
}

These are very simple code we have created but the idea here is to demonstrate shared libraries not C programming. In the library code we have one function display_uid() and this function can be accessed from any program that is linked to the library. This saves space and code maintenance. You can see from the main program that it is easy to reference multiple lines of code with the single line calling the function.

Compile the Library Module

gcc -c -fPIC displayuid.c
gcc -shared -o libdisplayuid.so displayuid.o

Deploy the Module

The module can be left in the users home directory and referenced through the LD_LIBRARY_PATH variable. This would be common for developers until they were ready to deploy the finished module. We will assume development is over and we want it deployed to the system.

mkdir -p /usr/local/lib/tup
cp libdisplayuid.so /usr/local/lib/tup

Then edit the file /etc/ld.so.conf.d/libtup.conf

/usr/local/lib/tup

With the path set we can run ldconfig to update the module cache

ldconfig

Compile the Main Program

gcc -L/usr/local/lib/tup standard.c -o standard -ldisplayuid

The upper case L says where to look for the modules and the lower case l the name of the module omitting the starting lib and ending .so .