Static C Libraries
Introduction
Before starting to talk about the subject matter, let us take a brief look at the compilation phases of a C program.
There are basically four phases:
- Pre-processing
- Compilation
- Assembly
- Linking
In this article, we will focus on the static libraries and their role in the linking phase of a program. But, first of all, let us define a library.
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 the same code over and over again, we can archive it and extract it from something that has already been written and optimized.Why use libraries?
What is a static library and how do they work?
How to Create a C Static Library on Unix like System
gcc -Wall -pedantic -Werror -Wextra -c my_math_func.c print_alphabet.cmy_math_func.o print_alphabet.oar -rc libname.a *.oThis command creates a static library named "libname.a" and puts copies of the object files "my_math_func.o" and "print_alphabet.o " in it.
Flag description:
-r Insert object files or replace existing object files in the library, with the new object files.
-c Create the library if it doesn't already exist.
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 will not matter during compilation.
Let's index it using the ranlib command:
ranlib libname.aOther way is using -s flag in ar command:
ar -rcs libname.a *.oIn order to list the names of the object files in our library, we can use the ar command with -t flag:
ar -t libname.aHow to use them?
void print_alphabet(void);
int main(void)
{
print_alphabet();
return (0);
}gcc main.c -L. -lname -o main$./main
abcdefghijklmnopqrstuvwxyz
Comentarios
Publicar un comentario