Compiling static libraries in Linux can be broken down into several steps. I'll illustrate this process with a simple example.
Step 1: Writing Source Code
First, we need to write some source code. Suppose we have a simple C function that we want to compile into a static library. For example, we have a file math_functions.c with the following content:
c// math_functions.c int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; }
We also need a header file math_functions.h with the following content:
c// math_functions.h #ifndef MATH_FUNCTIONS_H #define MATH_FUNCTIONS_H int add(int a, int b); int subtract(int a, int b); #endif
Step 2: Compiling Source Code to Object Files
Next, we need to use a compiler (such as gcc) to compile the source code into object files. This step does not generate an executable file but produces object files (with a .o suffix). Execute the following command:
bashgcc -c math_functions.c -o math_functions.o
The -c flag tells the compiler to generate object files (.o files) rather than an executable.
Step 3: Creating the Static Library
With the object files, we can use the ar command to create a static library. Static libraries typically have .a as their file extension. Execute the following command:
bashar rcs libmath.a math_functions.o
rindicates inserting the file and replacing existing files in the library.cindicates creating the library if it doesn't exist.sindicates creating an object file index, which can speed up the search during linking.
Now, libmath.a is our static library.
Step 4: Using the Static Library
Now that we have the static library, we can use it in other programs. For example, we have a main.c file with the following content:
c// main.c #include "math_functions.h" #include <stdio.h> int main() { int sum = add(10, 5); int difference = subtract(10, 5); printf("Sum: %d, Difference: %d\n", sum, difference); return 0; }
We can compile and link the static library as follows:
bashgcc main.c -L. -lmath -o main
-L.tells the compiler to look for library files in the current directory.-lmathspecifies linking with the library namedlibmath.a(note that the prefixliband suffix.aare omitted).
After executing the above command, we can run the generated program:
bash./main
This briefly outlines the complete process of compiling source code into and using static libraries in Linux.