How to create and use Dynamic Libraries in C

Miguel Pacheco
3 min readMay 4, 2021

Hello and welcome to another blog. In this case i want to talk to you about Dynamic Libraries.

In my last article i give a explanation of how to create and use static libraries. If you want to read it, please check this blog!

Differences between a dynamic and a static library

Dynamic libraries unlike static libraries (which consists can be used by multiple programs but once the program has compiled, it’s no longer possible to change the different pieces of object code in an executable file because all the code is contained in a single file that was statically linked when the program was compiled) consist of separate files containing separate pieces of object code. These files are dynamically linked to form a single piece of object code.

How to create a Dynamic Library (in Linux)

In order to create a Dynamic Library in linux simply we need to type gcc *.c -c -fPIC and hit return. This command generates one object file (.o) for each source file (.c). The -fPIC flag ensures that the code is postition-independent. This means it wouldn’t matter where the computer loads the code into memory. Some OS (operating systems) and Processors need to build libraries form position-independent code. The -c option just ensure that -o file isn’t linked yet

Next type in the terminal the next command: gcc *.o -shared -o liball.so (substitute the all for your library name). The wildcard * tells to the compiler to compile all the .o files into a dynamic library which is specified by the -shared flag. The naming convention for Shared libraries is such that each library name must start with lib and end with .so

Finally we need to export the path for libraries so that programs know where to look for them by executing the next command in our terminal: export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH

How to use a Dynamic Library (in Linux)

The objective of create dynamic libraries is to use it with other programs. You can compile your code in your terminal using the next command:

gcc -L test_code.c -ltest -o test_code

Where test_code.c in this case is the source code, needs to be listed before the -l flag. The -l combined with test tells to the compiler to look a dynamic library called libtest.so, while the -L tells to the compiler to look in the Current Directory

#include "holberton.h"int main(void)
{
_puts("Hello!");
return (0);
}

Typing gcc -L test_code.c -ltest -o test_code generates an executable file called test_code. In order to achieve this the compiler looks for throught the library (in this case test) that is specified with the -l flag for _puts function. Later we execute the test_code using ./test_code and give us the output: Hello!

--

--

Miguel Pacheco

Student at Holberton School | Aspiring to be a Front-End Web developer