A static library is a set of functions and variables which can be added to the target application at compile time. In Linux static libraries has an extension .a. Archive files are made up of object files ( Extension is .o ). The name of the static library should start with lib. For example libtest.a is a valid static library name.
Creating the Static Library File
The command ar is used to create static libraries.
The procedure is described below.
Let target.c be the source file to which static libraries are to be linked.
Let p1.c and p2.c contain the functions to be added to the static library libtest.a.
gcc p1.c creates p1.o and gcc p2.c creates p2.o.
The command to create the static library libtest.a is shown below,
ar -rcs libtest.a p1.o p2.o
Storing & Linking the Static Library File
- Store the static library in a standard directory like /usr/local/lib.
gcc target.c -ltest
- Store the static library in a directory you have created. For example in /usr/student/mylib.
gcc target.c -L/usr/student/mylib -ltest
The command nm can be used to find out the object files stored inside a static library file.