Difference between Static and Shared libraries

Usf Belhadj
3 min readMay 4, 2020

A static library is like a bookstore, and a shared library is like… a library. With the former, you get your own copy of the book/function to take home; with the latter you and everyone else go to the library to use the same book/function. So anyone who wants to use the (shared) library needs to know where it is, because you have to “go get” the book/function. With a static library, the book/function is yours to own, and you keep it within your home/program, and once you have it you don’t care where or when you got it.

In computer science, a library is a collection of non-volatile resources used by computer programs, often for software development. These may include configuration data, documentation, help data, message templates, pre-written code and subroutines, classes, values or type specifications.

A library is also a collection of implementations of behavior, written in terms of a language, that has a well-defined interface by which the behavior is invoked. For instance, people who want to write a higher level program can use a library to make system calls instead of implementing those system calls over and over again. In addition, the behavior is provided for reuse by multiple independent programs. A program invokes the library-provided behavior via a mechanism of the language. For example, in a simple imperative language such as C, the behavior in a library is invoked by using C’s normal function-call. What distinguishes the call as being to a library function, versus being to another function in the same program, is the way that the code is organized in the system.

Static Libraries :

A Static library or statically-linked library is a set of routines, external functions and variables which are resolved in a caller at compile-time and copied into a target application by a compiler, linker, or binder, producing an object file and a stand-alone executable. This executable and the process of compiling it are both known as a static build of the program. Historically, libraries could only be static.

To create a static library, we need to use the following command:

```ar rc liball.a dog.o cat.o bird.o``````ranlib liball.a``````gcc main.c -L -l<filename>```

Shared Libraries :

Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files.
These are linked dynamically simply including the address of the library (whereas static linking is a waste of space). Dynamic linking links the libraries at the run-time. Thus, all the functions are in a special place in memory space, and every program can access them, without having multiple copies of them.

To create a dynamic library, write the following command:

```gcc -g -fPIC -Wall -Werror -Wextra -pedantic *.c -shared -o liball.so``````export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH``````gcc -g -wall -o app app.c liball.so```

--

--