Static vs Dynamic Libraries
Why using libraries in general
In computer programming, a library refers to a collection of files, programs, routines, scripts, or functions that can be referenced in the programming code. These libraries are more complex than routines, optimized, and may even be designed by the same programmers behind the programming language. Libraries are just a bunch of files with functions stored inside!
What is the difference between a static library and a dynamic (shared) library?
Static libraries are better for quickly getting a library up and running, but it also has drawbacks. It gets compiled into every program that uses it; you have to manually update every program that uses it when you edit your library.
Dynamic libraries are nice because they load only 1 copy of themselves in memory when you run a program, less memory is used when running multiple programs using the library. The other benefit is that your programs don’t need to be recompiled when you recompile your shared library.
How do they work?
When writing code, we often use libraries to help us fill in the gaps when we don’t feel like reinventing the wheel… Which is great! Let’s not reinvent things just for the sake of working hard.
By using libraries, the programmer can concentrate on the unique aspects of the application being developed.
How to create a static library (Linux only)
First, you will need to create .c files containing the functions in your library.
Next, you will create a header file.
Then you will compile library files.
gcc -c lib_mylib.c -o lib_mylib.o
Finally, create a static library. This step is to bundle multiple object files in one static library (see ar for details). The output of this step is a static library.
ar rcs lib_mylib.a lib_mylib.o
Now our static library is ready to use. At this point we could just copy lib_mylib.a somewhere else to use it. For demo purposes, let us keep the library in the current directory.
Recommended by LinkedIn
How to create a dynamic library (Linux only)
First things first: we need to get all of the functions we want to use in one place. However you do this, just make sure to compile those functions as object files, and use the flag -fpic or -fPIC to let the compiler know you’ll be turning it into a dynamic library.
For example:
gcc -c -fPIC -Werror *.c
If everything compiles, then we can turn them into a library!
Syntax:
gcc -shared -o libpuppies.so *.o
Fantastic, you have created a new library!