Libraries in C: Static & Dynamic

Bárbara
3 min readSep 16, 2019

When starting a program in C, we usually use header files so the program can run with the functions we are going to use. The program needs these header files which can be either your own or the standard one; Libraries, are something similar, they carry the same responsibility, make the program run but the difference is that libraries are a collection of pre-defined functions compiled in a single one.

There are two types of libraries, static and dynamic, each one with a different functionality.

So, let’s get into dynamic libraries

Or commonly called shared libraries are a collection of functions compiled and stored in an executable with purpose of being linked by other programs at run-time.

To create one, start by writing this command in the shell.

  1. The first step consist of the compilation of the files.
  • -c compiling of files but not linking them.
  • -fpic or -FPIC a requirement for dynamic libraries.
  • -Wall -pedantic -Werror -Wextra are flags of the gcc to avoid mistakes.

After being compiled, the library is created with the following command:

2. Creation of the library with .o files

  • -shared for dynamic or share library.
  • -o output of the file
  • -nameoflibrary which is the name of library you want to create with the suffix .so(shared object)
  • -file.o is the file or files previously compiled but with the .o suffix

To look if the library was successfully created, type

Will look for the library
  • -la list all archives including the hidden ones.

And to display all the functions it contains, type

  • -nm examine the files and display the content of those files.
  • -D stands for dynamic.

Static libraries

Also a collection of files containing functions and variables. They end up with the .a suffix.

To create them, type the following command in the shell

  1. Compilation of files
  • -c compiling of files but not linking them.
  • file.c file or files to be compile and include to the library.

2. Creation of Static library

  • -ar a stands for archive and r stands for replace.
  • libraryname.a Is the name of the library, the suffix .a indicates static library
  • file.o is the file or files previously compiled but with the .o suffix

Difference between Static & Dynamic libraries

This image shows the difference between both libraries

From GeeksforGeek: https://www.geeksforgeeks.org/difference-between-static-and-shared-libraries/

To conclude with libraries, both libraries are a collection of functions which, not said before, are usually done by us, making them our own, kind of a personalized library.

-That was all. Hope you enjoyed and learned.

--

--