Static Libraries are a collection created using the archive (ar)program, To be exact it’s a collection of ordinary object files containing all symbols required by the main program to operate.
They permit users to link to programs without having the need to recompile a code, it saves recompilation time; however, static libraries are hardly used today, they aren’t as popular as they once used to be because of the advantages of the shared libraries. Static Libraries are often useful to developers wishing to permit programmers to link to their libraries but don’t want to give the source code of the library itself.
How to create a static library?
let’s take an example of a static library called “libholberton”.
- 1st step is to regroup all relevant files into one directory including the hedear (.h) file, making sure it contains the #ifdef HEADERFILE_H, the #define HEADERFILE_H and ends with #endif.
- 2nd step is to compile all the (.c) files and Turn them into an object file (.o) using the command “ $ gcc -c *.c”
- 3rd, Once the (.c) files compiled to their respective oject files we creat our library using the GNU “ar”. In our case this would be the command to use “ $ ar -rc libholberton.a *.o”
- 4th passing to the next step; the “ranlib” step to index our library. The index lists each symbol defined by a member of an archive that is a relocatable object file. “ $ ranlib libholberton.a”
- 5th we can check the content of our library using the “ar” option “-t”. “ar -t libholberton.a”, we can always check the symbols in our libraries as well using the command “nm” in our case “ nm libholberton.a”
And just like this we finished creating our static library. To put it into use let’s say we have a “main.c” file that needs to be executed we can use :
“ gcc main.c -L. -lholberton -o main”
L : Specifies the path to the library for example to point to the current directory -L/home/tmp to point to home/tmp directory.
finally all we have to do now is to run our main file by using “ ./main.c”.
Static linking is very easy however it have some disadvantages for example if the code is updated you need to recompile the program into a new executable, Not to mention that if you find a bug and have to fix it and recompile you’re going to through pain since the library contains a copy of the executable of every program.That’s why static libraries lost their fame and been replaced by Dynamic or shared Links.