How to Create a Dynamic Library in C

Thomas Francis
2 min readMay 4, 2021

Libraries are used in C to ensure that our code is reusable and organized. One type of library in C is the Dynamic Library. The Dynamic library consists of separate pieces of object code. Because of this modularity, it’s possible to alter the source code without needing to recompile the entire program. This flexibility, however, comes at the cost of final runtime speed. For comparison, static libraries are more efficient than dynamic libraries in the final product. Dynamic libraries would be best utilized for application development while static libraries would be preferred in the final product.

To create a dynamic library in Linux:

1. Create object files for all C files (.c) that you would like to put in the dynamic library.

gcc *.c -c -fPIC

The -fPIC flag means that code is position-independent, as in it’s independent of wherever its stored in memory on the computer. This allows the computer to decide where to load the memory during runtime.

2. Create the dynamic library.

gcc *.o -shared -o

Substitute the “all” from “liball” with the desired library name. The file name must begin with a “lib” and end in a “.so”.

The “-shared” flag specifies that we’re creating a dynamic library to the compiler.

Dynamic Libraries can be used in the following way:

gcc -L test_code.c -lholberton -o test_code

Where “-lholberton” flag has two parts. The “-l” tells the compiler to look for a dynamic library and the “holberton” part is the name of the dynamic library after the “lib” prefix. This flag looks for “”

The “-L” flag instructs the compiler to look for the library in the current directory.