What is and how to create C static libraries
Definition
Static libraries are just collections of object files that are linked into the program during the linking phase of compilation, and are not relevant during runtime.
Previous image shows the difference between Static and dynamic libraries, where static linking compile at time. In this post we’ll only talk about static library.
Creating a static library
There is a program called ‘ar’ that means ‘archiver’. This program can be used to create static libraries, modify object files in the static library, list the names of object files in the library, and so on. ie.
first, we must have our .c files in current working directory. Let’s check with ls *.c command.
Then, compile all files with gcc or cc command. ie.
gcc -Wall -pedantic -Werror -Wextra -c *.c
Now, it’s time to create the static library. Use next command.
ar -rc libholbertonschool.a *.o
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.
To display the table to listing the contents of archive, use -t option.
ar -t libholbertonschool.a
After an archive is created, or modified, there is a 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. The command used to create or update the index is called ‘ranlib’. ie.
ranlib libholbertonschool.a
Using Library in a program
After we created our archive, we want to use it in a program. This is done by adding the library’s name to the list of object file names given to the linker, using a special flag, normally '-l'
. ie. gcc main.c -L. -lholbertonschool -o o example
This will create a program using object file “main.c”. The ‘l’ before name file “holbertonschool” with extention ‘.a’ doesn’t need the ‘lib’ and extention.
'-L'
option - this flag tells the linker that libraries might be found in the given directory ('.', refering to the current directory).
Finally, when you execute the file, the output will show all the logic implemented in the functions called in different libraries. ie.
This is the main.c file, where make a call in function _puts. That function is located and linked in static library when file was compiled.The exit will return success.