乐闻世界logo
搜索文章和话题

How to compile a static library in Linux?

1个答案

1

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:

bash
gcc -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:

bash
ar rcs libmath.a math_functions.o
  • r indicates inserting the file and replacing existing files in the library.
  • c indicates creating the library if it doesn't exist.
  • s indicates 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:

bash
gcc main.c -L. -lmath -o main
  • -L. tells the compiler to look for library files in the current directory.
  • -lmath specifies linking with the library named libmath.a (note that the prefix lib and suffix .a are 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.

2024年7月22日 17:35 回复

你的答案