Static Libraries in C
A library is a collection of items that you can call from your program.
Libraries contain variables and functions within them. It is known as library to certain types of files that we can import or include in our program.
It obviously has a lot of advantages, not least of which is that you can save much time by reusing work someone else has already done and be more confident that it has fewer bugs.
Some examples of popular libraries are:
What is a Static library?
The most straight forward way of using a library function is to have the object files from the library linked directly into your final executable, just as with those you have compiled yourself. When linked like this the library is called a static library, because the library will remain unchanged unless the program is recompiled.
Static libraries are object files that are later combined with another object to form a final executable.
By convention they have the prefix lib and the suffix .a
How to create a static library?
To create a static library using GCC we need to compile our library code into an object file so we tell GCC to do this using –c
$ gcc -c -Wall -Werror -Wextra *.c
After this process, we will have .c files compiled into object files '.o' which are necessary for the library.
After creating object files we use the GNU ar command to create our final library/archive.
Recommended by LinkedIn
$ ar -rc libname.a *.o
- ar is a UNIX command for creating and maintaining library archives
- -r is used to replace or add files to archive
- -c is used to create a new archive file
- libexample.a is the name of the file with the extension '.a' which stands for archive
- And the final step of the command is the selection of all object files
How to use them?
After creating the library (archive file) we use it in a program.
gcc filename.c -L . -lexample -o filename
- gcc (GNU Compiler Collection) - command to compile C files
- filename - name of the file
- -L . - tell the linker that the libraries might be found in the current directory '.'
- -l - links the C file with the library file
- example - the name of the static library (check notes at the end of the article)
- -o is used to change the name of the executable file
- filename - name of the executable file