The differences between static and dynamic libraries
In programming, a library may be a collection of pre-compiled pieces of code which will be reused during a program. Libraries simplify life for programmers, therein they supply reusable functions, routines, classes, data structures than on which they will be reused within the programs.
Static Libraries: A Static library or statically-linked library may be a set of routines, external functions, and variables which are resolved during 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 therefore the process of compiling it are both referred to as a static build of the program. Historically, libraries could only be static.
Why use libraries?
As mentioned before, libraries allow us to store function definitions, aka pieces of code that will be used in our executable program. It makes the tedious task of compiling an enormous number of source files together avoidable, isn’t it great? Libraries are made from object files, with the extension ‘.o’, and may be made on Linux with the gcc compiler. Then, it’s up to us if we would like to make a static or shared library.
How libraries work
Once the libraries are created, they will be linked with the file containing the most function, or entry point, with gcc. Then, the code of the functions utilized in the program are going to be linked into the executable program, and it'll be able to run!
How to create libraries (Linux only)
Let’s use as an example the file “my_file.c”. In both cases, we'd like to make object files first. this is often through with the subsequent commands:
Static:
$ gcc -c my_file.c
Dynamic:
$ gcc -c -fPIC my_file.c
We use an additional flag for dynamic libraries: ‘-fPIC’ or ‘-fpic’. This makes the code within the library position-independent. PIC is code that works regardless of where it's placed in memory. Why does it matter? Because several programs can use an equivalent shared library, the library will have different addresses in memory for every program. and that we still want our programs to possess access to the code wherever it's stored.
Now we will create the ‘mylib’ library with our object file. Here’s how:
Static:
$ ar rc libmylib.a my_file.o
Dynamic:
$ gcc -shared -o libmylib.so my_file.o
How to use libraries (Linux only)
Now that we've our library, we've to use it to compile and make our program. Let’s say our entry point is within the ‘main.c’ file, and that we want to call our program ‘test’. Here’s the command to compile the program with our library in both cases:
$ gcc -L. main.c -lmylib -o test