Static and Dynamic Libraries in Linux

mandonuno
mandonuno
Apr 17, 2018 · 2 min read


Libraries in C:

A C library is a collection of named functions, such as The pros of using C libraries are that they allow us to reuse these functions within our programs, saving us time, rather than having to rewrite the code for these functions every time we need them. These libraries come in two forms; static or dynamic(shared) libraries.

Static Libraries:

  1. Static libraries are .a files
  2. Statically linked files are larger in size because external programs are built into the executable files
  3. Static linking is the process of copying all library modules used in the program into a final executable
  4. Programs that use statically linked libraries are usually faster than those that use shared libraries
  5. All code is contained in a single executable module
  6. A static library’s code is stored into the final executable file and cannot be modified without having to re-compile the code

Dynamic libraries:

  1. Shared libraries are .so files
  2. Dynamic linking is performed at run time by the operating system
  3. Dynamic linking has only one copy of the shared library in memory, which significantly reduces the size of executable programs
  4. Multiple running applications can use the shared library without needing to have it’s own copy

Creating a Static Library (Linux only):

Using gcc to compile your C programs, you must include the . This tells the compiler to stop and return an object file (.o) for each source file:

gcc -Wall -pedantic -Werror -Wextra -c *.c

Once each C program has its own object file you can now archive the static library using the command:

ar -rc staticlibraryname.a *.o

Creating a Dynamic Library (Linux only):

Same as creating the static library we will use the gcc command with flags to compile all C files and create object files for each, also including the . The flag is used to compile our file into position-independent code (PIC), which allows the programs inside the library to be executed, regardless of its location in memory.

gcc -Wall -pedantic -Werror -Wextra -c -fPIC *.c

Once the compiler has created the object files, we can now create our dynamic library using the command:

gcc -shared -o staticlibraryname.so *.o

The option flag tells the compiler to produce object files which can be linked together with other objects to form an executable making the library dynamic(shared). The option simply tells the compiler what to name the file to be created.

Finally, in order to use our dynamic library, we’ll have to add it to our environment using the command:

export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH