- Why use libraries
- How they work
- How to create them
- How to use them
Why use libraries?
The static libraries are used for the reason of use fuctions that we have already written somewhere in the past, so we can recycle already written code, either by us or whoever else, and be more efficient because we will just write a function once and then we can call it when we compile the program with the library where the function is saved.
When should we use the static libraries?
You should use the static libraries only if you want to make the compilation time go faster without caring about memory. Because if you compile different programs multiple times the memory will make a copy of the static library each time you use it. If you want to save memory space then you should choose to use a dynamic library.
How do the C static libraries work?
The library accepts only object files, that means, files that are assembled by the compiler, then all of those object files are reserved inside a file, then when we compile a program with the main function and that calls any of the functions inside the library, we can tell the compiler to compile the main file and link with the program file the library that has all the functions we need.
How to create a C static library?
The basic we use to create it is called
'ar', for 'archiver'. This command can be used to create static libraries (which are actually archive files), modify object files in the static library, list the names of object files in the library, and so on. So, for example, we can use this command like this:
ar rc libutil.a util_file.o util_net.o util_math.o
This command creates a static library named 'libutil.a' and puts copies of the object files "util_file.o", "util_net.o" and "util_math.o" in it. The
'c' flag tells ar to create the library if it doesn't already exist. The
'r' flag tells it to replace older object files in the library, with the new object files.
After an archive is created, or modified, we need to index it. This index is later used by the compiler to speed up symbol-lookup inside the library, and to make sure that the order of the symbols in the library won’t matter during compilation. To create or update the index we use
'ranlib', just like this:
How to use the static library?
Now is time for us to use the library we’ve just made, for that when we compile any program with the gcc compiler, we will need the ‘-l’ flag to specify the name of our library and the flag ‘-L’ to specify where is the library.
gcc main.c -lutil -L. -o main
Here we put the name ‘util’ with neither the prefix ‘lib’ nor the suffix ‘.a’, the linker puts that name in the back of the library, so for next ocations the linker will recognize it with that name, also we defined the path or the directory where the library is, that’s what the ‘.’ after ‘-L’ means, and what it is saying yo the program is: “That library is in this directory”. Otherwise you should specify the path where the library is folded.