Creating a Static Library in C

A static library in C is a collection of object files that are linked into the program at compile-time. The final executable contains all the code from the static library, making it self-contained.

Steps to Create a Static Library:

  1. Write the Source Files:

    Example:

    // file: add.c
    int add(int a, int b) {
        return a + b;
    }
    
    // file: sub.c
    int sub(int a, int b) {
        return a - b;
    }
    
    // file: mathlib.h
    int add(int a, int b);
    int sub(int a, int b);
    
    
  2. Compile the Source Files into Object Files: Use the gcc compiler to create .o object files.

    gcc -c add.c sub.c
    
    
  3. Create the Static Library Archive: Use the ar (archive) command to bundle the object files into a static library (.a file).

    ar rcs libmathlib.a add.o sub.o
    
    
  4. Use the Static Library in a Program: To use the static library in a program, link it during the compilation of the main program.

    Example:

    // file: main.c
    #include "mathlib.h"
    #include <stdio.h>
    
    int main() {
        printf("Sum: %d\\\\n", add(3, 4));
        printf("Difference: %d\\\\n", sub(10, 5));
        return 0;
    }
    
    

    Compile and link the program with the static library:

    gcc main.c -L. -lmathlib -o main
    
    
  5. Run the Program: After compiling and linking, run the program:

    ./main
    
    

Advantages of Static Libraries:

Disadvantages:

Key Commands: