Dynamic Libraries v Static Libraries

Wiston Venera Macías
2 min readDec 14, 2020

Long story short, Static libraries are locked into a program at compile time. On the other hand, Dynamic libraries or shared libraries exist as independent files.

A static library (SL) can’t be modified and is more secure because of its nature, but if you need to change some behavior you have to recompile every program with every copy of your SL. With DL (dynamic libraries), you can modify the behavior of the functions that you are using on your program without the need to recompile your main program. But using a DL is less secure because of its nature. So, someone can change the behavior of the library or change the entire library and this can affect all your programs that use that library because every program would be pointing to the same DL.

DL creation on Linux

First of all you need copy all our .c files that we want to include in the library to a folder and run the next command in that folder: “gcc *.c -c -fpic” the fpic flag is used to specify that the generated machine code is not dependent on being located at a specific address in order to work. As we did with the SL we use the -o flag to generate .o files (machine level instruction files).

The next command we need to use is “gcc *.o -shared -o liball.so”. The flag -shared is used to specify that the library is going to be a DL. We need to take care of the name of our library, because the compiler indetifies a library by begining of the name and the extension. For that reason our output is liball.so, where the 3 first letters stand for library and the extension .so stands dynamic.

Now we need to make our DL available for every program so we create a global variable for it. export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH

If you don’t remeber how to create a SL click on this text.

We are just about to end. The command “gcc code.c -L. -lall”. The flag -l is used to specify that we want to include library files; and the ‘all’ next to -l is used to look for the library liball.so. If our library is called libfoo.so the flag would be -lfoo. And the flag -L. is to specify to the compiler that the library is in the current directory, and that’s all. See you on a next story.

--

--