C Static libraries, How they work; Why and how we use them and how to create one
David Stiven Perlaza Valencia
DesarrolladordeSoftware|Backend|Frontend|Python|Flask|Django| SQL|JavaScript|React Js|Java|SprintBoot|NoSQL|PostgreSQL
1. What is a Static library
A static library which is a statically linked library is a set of routines, external functions and variables that are resolved in a caller called compile-time and copied into a target application by a compiler.
Any static library function can call a function or procedure in another static library. The linker?and loader handle this the same way as for kinds of other?object files. Static library files may be linked at run-time?by a?linking loader.
2. How to create a static library
Static libraries can be easily created. First we need to create the object files using the command
gcc -c *.c
This command will stop the compiling process before the linking phase and will create object files out of our .c files.
Next we will be using the "ar" command which is a program creates, modifies, and extracts from archives. An archive is a single file holding a collection of other files in a structure that makes it possible to retrieve the original individual files (called members of the archive).
领英推荐
ar -rcs libname.a .*o
This commands will create a library called "libname.a" out of all our object files.
3. How to use static libraries
After creating our static library to use it we need to include it in our program.And when compiling program files, we have to tell the compiler to use the library files and where to find them. ‘-l’ tells it we want to include library files. And ‘all’ tells it to look for the library liball.a. It’s important to leave the ‘lib’ and ‘.a’ out of the flag because the compiler already identifies library files that way. ‘-L.’ tells the compiler it can find the library file in the current directory.
gcc main.o -L. -llibholbertonschool -o prog
4. How static libraries work
The way static libraries work is by supplying the executed program with an indexed list of all symbols such as variables, functions.. that are required by the program during the linking phase of compiling. They won't be required during run-time because all their components are imported into the executable file.