`

Static Library vs. Dynamic Library

Static Library:

Dynamic Library:


Compilation Process

When compiling a C program, the compiler generates object code. What is an object file? In our case, it is a file that contains object code and typically has a .o extension. Then, the compiler also invokes the linker. One of the main tasks of the linker is to make the code of library functions (e.g., printf(), scanf(), sqrt(), etc.) available to your program. This task can be accomplished in two ways by the linker:

By convention, the static library has the prefix lib and the suffix .a. Example: lib_myLibrary.a.

Library_image

Step-by-Step Example: Creating a Static Library in C

Step 1: Create the Header File

Create a new text file with a .h extension. For example, you could name it addition.h.

Define Function Prototypes

In the header file, define the function prototype for the add function. This allows other source files to know about the function and its parameters without seeing the implementation details.

addition.h:

// Function prototype for addition
int add(int a, int b);

Step 2: Save the Header File

Save the header file in the same directory where your source code files are located.

Step 3: Include the Header in Source Files

In any source file where you want to use the add function, include the header file using the #include directive.

main.c:

#include <stdio.h>
#include "addition.h" // Include the custom header

int main() {
    int result = add(10, 5);
    printf("Addition result: %d\n", result);
    return 0;
}

Step 4: Create the Implementation for the Header File

Write the implementation of the add function in a .c file.

addition.c:

int add(int a, int b) {
    return a + b;
}

Step 5: Compile the Library Implementation

Run the following command to compile the addition.c file into an object file.

gcc -c addition.c -o addition_output.o

Step 6: Create the Static Library

Use the ar command to bundle multiple object files into a static library:

ar rcs lib_myLibrary.a addition_output.o

Step 7: Create the Main Program

main.c:

#include <stdio.h>
#include "addition.h"

int main() {
    printf("Addition is %d", add(2, 3));
    return 0;
}

Step 8: Compile the Program with the Static Library

Compile the program using the following command:

gcc -o test_output main.c -L. lib_myLibrary.a

Explanation of the -L. Option

In C and C++ programming, the -L. option is used to specify a directory where the linker should look for libraries during the compilation process. Specifically, it adds the current directory (.) to the list of paths that the linker searches for libraries.

If you have a custom library named mylibrary located in the same directory as your source code, you might compile and link your program like this:

gcc -o my_program main.c -L. -lmylibrary