What Is The Difference Between Dynamic And Static Libraries

Yago Martinez-Falero Hein
2 min readDec 14, 2020

As a software engineer, you often go about solving big problems by breaking them down into several smaller problems. Most of the time, you want to write one function to solve one problem. For example, you can create a function called _strlen() to calculate the length of a string.

This will be the kind of function you’ll use a thousand times while coding. It’s OK to rewrite them each time you start a new program. But it’s better if you could save yourself the hassle, and that’s what libraries are all about: making functions reusable in multiple programs.

In this article, we will cover: the difference between static and dynamic libraries, their pros and cons, how they work, how to create them and, how to use them.

Static vs Dynamic Libraries

  • Static libraries, even if they can be used in multiple programs, are locked into the program at compile time.
  • Dynamic libraries can also be used in several programs but they exist as separate files and are not locked to the executable file.

Upsides And Downsides

How To Create Them

Dynamic Libraries (Linux only)

In your shell type the following commands:

gcc *.c -c -fpic

This command essentially generates one object file .o for each source file .c . You need to make sure you prepare you .c files before compiling.

Flags:

  • -fPIC ensures that the code is position-independent.
  • -c option ensures that each .o file isn’t linked yet.
gcc *.o -shared -o liball.so

The wildcard * tells the compiler to compile all the .o files into a dynamic library which is specified by the -shared flag.

The prefix lib is a convention for dynamic library files which end with the extension .so .

export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH

This will export the path for libraries so that programs know where to look for them.

Static Libraries (Linux only)

In your shell type the following commands:

gcc *.c -c -fpic

We start the same way by creating object files from our .c files. Then we archive the library using:

ar rcs liball.a *.o

Now both our static and dynamic libraries are ready to be used.

How to use your libraries

It’s very simple to use your libraries. You will have to include them at compilation using the following command:

gcc -L -liball YOUR_C_FILE -o YOUR_EXEC_NAME

Here the -L flag tells it we want to include library files.

--

--

Yago Martinez-Falero Hein

👨🏼‍💻 Entrepreneur and software engeneer // Former employee at TheFamily.co // 👨🏼‍🎓 Holberton School & Reverse Origins