Static Libraries in a nutshell
As you might know, one of the main responsibilities of the compiler is to invoke the linker that has the responsibility to make available the code of library functions required by the main program to operate. There are two ways to accomplish this task, by copying the code of library function to your object code, this is known as a Static Libraries, the other way is using Dynamic Libraries but, in this text, we will focus only on the first concept.
In a nutshell, a library is a collection of objects that you can call from your program to perform a task. Using libraries can save you a lot of time, there are tons of functions and problems that have been already resolved by other programmers. Instead of spending time trying to figure out the solutions for a specific problem, it is possible that you can find a library that has a proper solution for your problem, so you only need to make it available to your program.
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. The objects files from the library are linked directly into the final executable, this means that instead of having to take a look for each entity of separate parts of the disk, the program needs only to reference a single archive object (.a) that own the entities together and the library will remain static unless the program would be recompiled. This is a straightforward way of using a library because the final result will be executable with no dependencies. The bad side is, if many programs use the same libraries, each program will carry a copy of that library that resulting in inefficiency.
Creating a Static Library:
1. Gather all relevant files into one directory including header file .h that contains the prototypes. Make sure that the header file contains the wrapper (#ifndef and #endif) to prevent multiple includes.
2. Compile all .c files. Use the -c option so that the compiler doesn’t link the object files yet, but instead creates an equivalent object file .o for each source .c file.
3. Archive all object .o files to a static library .a file. Use the -c command to create a file, use the -r command option to make sure that if the library file .a already exists, it will be replaced.
4. We’ve created a static library libmy.a (let’s move it to the same directory that entry-point resides). Now, we want to use it as a program. This is done by adding the library’s name to the list of object file names given to the linker.
As you could see, we can now run the executable program by typing ./quote which will print:
“At the end of the day, my goal was to be the best hacker”
- Kevin Mitnick