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.

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.
  • Faster execution: since all the code, and libraries are within the same executable file, its execution time is shorter than the files using dynamic libraries, this is more representative in big files with a considerable amount of functions and calls.
  • Portability: again, having all the needed code in one file, makes it easier to port the program from system to system.
  • Bigger files: due to its “all included” nature, using static libraries will result in bigger files.
  • 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
  • Smaller files: Only the main program code is in the executable file.
  • 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.
  • Not as easy to carry as static libraries: The library and the executable file are two separated files, and as such we have to carry both and export the library to the its PATH in every system we want to use it.
  • 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

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

Using a dynamic library.

gcc -L my_main_file.c -lholberton -o my_main_file
-L/home/username/my_library
  1. Gather the functions you want to add to a library.
  2. Compile all the .c files into object files ($ gcc *.c -c fPIC)
  3. Create the static library ($ gcc *.o -shared — o libmy_library.so)
  4. Export the path to the library

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store