Dynamic and Static libraries in Linux

Let’s continue getting the most out of some of those portable cleaver solutions (functions) we find to solve problems when coding: Let’s create a Dynamic Library.

On a previous article (see below) I shared about the different types of libraries in Linux, but only went deep into Static libraries, its pros and cons, how to create and use them. Now, let’s dive into dynamic libraries and find out what are their main differences, so we can get a better idea of what and when to use each.

Linking step. — LEFT — STATIC LIBRARIES: all main code and functions are copied into the executable file. — RIGHT — DYNAMIC LIBRARIES: libraries are stored in the PATH (memory place). The executable file only contains the program main code and the address of the libraries.
  • Portability: again, having all the needed code in one file, makes it easier to port the program from system to system.
  • Limited or more difficult updating process: We have to go through all the library creation and program compilation process every time we do a modification, update or any change to any of the functions contained in the library
  • Flawless updates: If we do any modification on any of the functions in the library, there is no need to compile the main program again, only the library, it is because when calling the function from the executable file, the system will look for where the link (address) points to, which should be the latest version of the library.
  • Longer execution times: Calling and getting the functions in the library implies a search in the memory address it was allocated, it means additional processes and waiting times, which may be representative in big files with a considerable variety of functions and calls.

Creating a Dynamic Library

Lets create a dynamic library called my_library.

export LD_LIBRARY_PATH=/home/username/my_library:$LD_LIBRARY_PATH

Using a dynamic library.

As we did with our static library article, when compiling it is necessary to specify that we are going to use a dynamic library.

gcc -L my_main_file.c -lholberton -o my_main_file
  1. Compile all the .c files into object files ($ gcc *.c -c fPIC)
  2. Create the static library ($ gcc *.o -shared — o libmy_library.so)
  3. Export the path to the library