Static Libraries in C .
Static library is a set of routines, external functions and variables which are resolved in a caller at compile time and copied into a target application by compiler , linker producing an object file and an executable.
Libraries are particularly useful for storing frequently used functions because you do not need to explicitly link them to every program that uses them. The linker automatically looks in libraries for routines that it does not find elsewhere.
So How to create and use a Static Library?
In order to create the library first thing we need to have all our functions in separate C files (files with extension .c)
$ gcc -c funtion_name.c
Here in this example we use the flag “-c” is to stop the compiler in producing the .o files in the end we give the .c file we want to compile
$ gcc -Wall -Werror -Wextra -pedantic -c *.c
$ ar -rc liball.a *.o
The command "ar" is used to create archive file (.a)
The flag “-r” is to replace-overwrite .o files (just in case that library exists already)
The flag “-c”to create the library if it doesn’t exist or appends to it if it does
The “liball.a” in this example is how we want to name the library but always with the lib- prefix and ".a"extension.
The flag “*.o” to add all object files (we can choose one or more by adding their names).
Recommended by LinkedIn
$ranlib library.a
you can list you library to se the content with the following command :
$ar -t libholberton.a
In this example it would look like this !
That is an example from my protect , it was my first library .
Cool at this point if we follow all the steps , we get our first static library!!
Now that we created it , lets see how to used it :
$ gcc main.c -L. -lall -o program_name
Use the command “gcc” to call the compiler.
The flag “-L.” is to tell the compiler to look for Libraries and the path to look at.
The flag “-lall” with this flag we are declaring the library’s name that we want to link (note that our library’s name is liball.a but we typed -lall, the linker needs only to know the custom name we give it and it will add automatically the preffix and extension)
The flag “-o program_name” is to defines the executable’s output name , you can run the command with out this flag and get the default output name “a.out".
I hope this information will be helpful to you , let's keep learning .