Differences between static and dynamic libraries

The Starry Night. Vincent van Gogh

Why do libraries exist?

Libraries are collections of functions which can be called from a program, and this can be done by embedding those libraries in the linking process when compiling the program. Libraries can come from your own creations or from open source code.

What is a static library in C?

Another useful step is to generate an index to the contents of the (.a) file before the compiling because this will reduce the time of the process. That index will be in the (.a) file and helps in the finding of the symbols of the functions.

What is a dynamic library in C?

How to create and use a dynamic library?

At first, we need to have all of our (.c) files in the current directory with a header file (.h) that contains the prototypes of our functions.

Then, we have to use two commands to compile those files:

gcc -fPIC -Wall -Werror -c *.c && gcc -shared -o liball.so *.o

the options for this process are as follows:

  • fPIC : This is a requirement for shared libraries that stands for “Position Independent Code”.
  • -Wall -Werror : standard error checks you should use
  • -c: compiles source files without linking.
  • *.c: selects all of your c files
  • -shared: Creates a shared library with a prefix of lib and a suffix of .so which stands for shared object.
  • -o: Places output in a file

To use a shared library is not as straightforward as the static library was. Once you create a shared library you will have to install it.

Usage:

  • Use this command to see the functions in your libraries.
  • -D: This refers to the symbols in the data initialization section
  • Update your LD_LIBRARY_PATH to include the directory where your library can be found
nm -D libholberton.so
  • Compile your program and include -L. to include the path to your library
  • Exclude the lib prefix and .so suffix to include your library
gcc -L. -o main.c program.c -lholberton

If you need more information about dynamically linked libraries:

http://cs-fundamentals.com/c-programming/static-and-dynamic-linking-in-c.php

--

--

Software and Chemical Engineer

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