`
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
.
Create a new text file with a .h
extension. For example, you could name it addition.h
.
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);
Save the header file in the same directory where your source code files are located.
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;
}
Write the implementation of the add
function in a .c
file.
addition.c:
int add(int a, int b) {
return a + b;
}
Run the following command to compile the addition.c
file into an object file.
gcc -c addition.c -o addition_output.o
Use the ar
command to bundle multiple object files into a static library:
ar rcs lib_myLibrary.a addition_output.o
r
: Replace existing files in the library.c
: Create the library if it does not exist.s
: Create a sorted index of the library for faster access.main.c:
#include <stdio.h>
#include "addition.h"
int main() {
printf("Addition is %d", add(2, 3));
return 0;
}
Compile the program using the following command:
gcc -o test_output main.c -L. lib_myLibrary.a
-L.
tells the linker to look in the current directory for libraries.lib_myLibrary.a
is the static library that contains the implementation of the add
function.-L.
OptionIn 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
-L.
tells the linker to search the current directory for libraries.-lmylibrary
tells the linker to look for libmylibrary.a
or libmylibrary.so
.