How to create and use dynamic libraries in C

Jaime Andrés Aricapa Pérez
2 min readMay 3, 2021
Photo by Gabriel Sollmann on Unsplash

The dynamic libraries consist of separate files containing separate pieces of object code. These files are dynamically linked together to form a single piece of object code. Furthermore, dynamic libraries contain extra information that the operating system will need to link the library to other programs. Giving the possibility of access to the memory because is conserved while using dynamic libraries since each application or program can access the dynamic library without needing an individual copy, as would be the case, if we were using static libraries. Also, as a special feature of this way of use libraries, is the ability to alter source code without recompiling the entire program, an enormous advantage against static libraries to reduce memory usage and execution speed at run-time.

First step: Create the library

To create a dynamic library in Linux, use this command and hit return:

gcc *.c -c -fPIC

This command generates one object file .o for each source file .c . The -fPIC flag ensures that the code is position-independent. This means it wouldn’t matter where the computer loads the code into memory. Some operating systems and processors need to build libraries from position-independent code so that they can decide at runtime where they want to load it into memory.

After the object files was created use this another command and hit return:

gcc *.o -shared -o liball.so (replace the part in bold with the desired name for the library).

The command uses a wildcard * to tell the compiler to compile all the .o files into a dynamic library which is specified by the -shared flag. The naming convention for dynamic libraries is such that each shared library name must start with lib and end with .so.

After the library had the dynamic feature, the next step is export the path for libraries so that programs know where to look for them by executing the following command:

export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH

Second step: Use the library

To use a dynamic library is required compile the desired program using this command:

gcc -L program.c -lholberton -o program

The command starts with list the program file before the -l flag. The expression, -l combined with holberton tells the compiler to look for a dynamic library called libholberton.so, while the -L flag tells the compiler to look in the current directory for the library file. An example of use of a dynamic library is the following:

#include “holberton.h”

int main(void)
{
_puts(“Hello World!”);
return (0);
}

Typing and executing gcc -L program.c -lholberton -o program would generate an executable file called program. In order to accomplish this, the compiler looks through the library that is specified with the -l flag for the _puts function object code. Executing program would give us the following output: Hello World!.

--

--