Static vs. Dynamic Libraries

Stephen Ranciato
2 min readSep 16, 2019

--

Quick guide

https://www.dementiajourney.org/wp-content/uploads/2017/10/desktop-wallpaper-books-wallpapers-bookshelf-old-ladder-book-library-vintage-cartoon.jpg

Why we use libraries

When we are writing programs it is important to be as efficient as possible. For this reason we want to remove the repetition by not having to continuously link each routine to every function that we write. Libraries remove the monotony of doing so by saving each precompiled routine into a collection.

How to create a dynamic library

1 ~ gcc -fPIC *.c -shared -o testlib.so

This will create a a shared/dynamic library named testlib.so

The two flags that may be unfamiliar are the -fPIC and -shared flags.

The -fPIC flag is used to create an object file with position independent code.

The -shared flag is used to actually create the shared library. This is why we end up with the library testlib.so

How we use dynamic libraries

We can use them with 2 simple steps.

1 ~ gcc -L main.c -testlib -o result

2 ~ export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH

The first step compiles whatever you have in your main file with the library we created and outputs an executable file named result. If you have not completed the second step the result executable file will not run.

The second step allows the linker to find the library that we have made. We find it by setting our environmental variable LD_LIBRARY_PATH . The command we use in particular, installs the library into your current working directory.

Differences between static and dynamic libraries

Static libraries are much faster than dynamic libraries.

Static libraries have to be recompiled every time you add new code.

Dynamic libraries allow you to dynamically add code to the executable without having to recompile.

--

--