Static vs Dynamic libraries in C!

What are they?

Both have their advantages and disadvantages. For starters, the nature of compiling the library into the output file means that any change to a static library involves a second step of re-compiling. Meanwhile, dynamic libraries are easy to modify and pass on to the necessary files. However dynamic libraries require more processing power at compile time, and also carry a higher risk of failure, as one bad file at execution will render the whole library useless. Static libraries come out on top in this regard as they are processed much faster at compilation.

Creating a library:

 gcc *.c -c -fPIC

which calls for every file ending in .c that hasn’t been linked (that’s the ‘-c’ part) regardless of where they are located in memory (and that’s the ‘-fPIC’ part). This will generate one object file (.o) for every .c file compiled. These files need to be compiled as well, so we call gcc *.o -shared -o liball.so. This commands takes every .o file and creates a dynamic library (-shared) where liball is a generic name for the .so file it outputs.

To create a static library: follow the same steps to create the object files and then simply archive the library using:

ar rcs liball.a *.o 

‘ar’ is the GNU archive program and rcs breaks down to the following: r- rewrite if existant, c- create if non-existant, and s- sort it.

Using a dynamic library:

gcc -L. example.c -lholberton -o example

In this example -L tells it to expect library files and -lholberton tells it to expect them to come from a libholberton.so file.