C static libraries
what is a library:
A library is a collection of code routines (functions, classes, variables, and so on) that can be called upon when building our program, so instead of writing it ourselves, we can go and get it from something that has already been written and optimized. That is where the idea behind libraries comes from. We are reusing blocks of codes that have come from somewhere else.
What is a static library:
In the C programming language, a static library is a compiled object file containing all symbols required by the main program to operate (functions, variables etc.) as opposed to having to pull in separate entities.
How to create static libraries?
1: To create a static library, we needthat we want to compile all library codes (*.c) into object files (*.o) without linking. To do that we are going to use the command below to specify to the compiler. In this case we will use gcc as compiler.
Flags description:
-c: Compile and assemble, but do not link.
-Wall, -Werro and -Wextra: These aren’t necessary but they are recommended to generate better code.
Note that the “*.c” matches all files in the current working directory with the “.c” extension.
2: Archive all of the object (.o) files into one static library (.a) file. Use the command option -r to ensure that if the library (.a) file already exists, it will be replaced. The command option -c should be used so that if the file doesn’t exist, it will be created.
3: To list the names of the object files in our library, we can use the ar command with the -t flag.
How to use them
Now our static library “libname.a” is ready to be used. we can use it in a program. This is done by adding the library’s name to the object file(s) given to the linker. First, let us create a C source file that uses the above created static library.
Flags description:
-L : Specifies the path to the given libraries (‘.’ referring to the current directory)-o : Place output in file file. If -o is not specified, the default is to put an executable file in a.out
BY: Alexander Forero
For :Holberton school