Static libraries vs Dynamic libraries

Felipe Balanta
3 min readDec 1, 2021

Libraries in the C programming language are a set of functions that are ready to use when called from a program.

They are files that allow us to carry out various functions without having to worry about how they are done but about understanding how they work, they allow us to make our programs reusable and make our code shorter.

Dynamic Libraries

The dynamic are a collection of object files which are referenced at build time to give the executable information how they will eventually be used, but they aren’t used until run time. In other words, these objects are dynamically linked into executables that use them.

How to create

To begin it is necessary to have the files that store our code.

we create our object files with the following command

gcc -c -fPIC *.c

Now we are going to create the dynamic library using the gcc command. You must use the -share flag to specify the dynamic library. Your library name must start with lib and end with the .so file extension.

gcc -shared -o libholberton.so *.o

And finally we must add an environment variable to the library so that our program knows where to look

export LD_LIBRARY_PATH = $ PWD: $ LD_LIBRARY_PATH

How to use

In order to use the library, the files must be compiled with the gcc command with the -L flag with the name of the library omitting the “lib” and the file extension “.so”

gcc -L. -lholberton *.c -o test

the static libraries are copied into our program when compiling, once we have the executable of our program if we wanted we could delete the library since it is already integrated in our program or we could use it for future projects

The dynamic library is not copied into our program when compiling it, when we have our executable and we are executing it, every time the code needs something from the library, it will look for it. If we delete the library, our program will give an error that it cannot be found.

Advantages and disadvantages

* A program compiled with static libraries is larger, since everything it needs is copied.

* A program compiled with static libraries can be taken to another computer without having to take the libraries.

* A program compiled with static libraries is, in principle, faster in execution.

* When you call a library function, you have it in your code and you don’t have to go read the dynamic library file to find the function and execute it.

* If we change a static library, the executables are not affected. If we change a dynamic, the executables are affected. This is an advantage if we have changed the library to correct an error (it is corrected automatically in all executables), but it is inconvenient if touching that makes us change the executables (for example, we have added one more parameter to a library function , ready-made executables stop working).

--

--