Introduction :
A “program library” is simply a file containing compiled code (and data) that is to be incorporated later into a program; program libraries allow programs to be more modular, faster to recompile, and easier to update. Program libraries can be divided into three types: static libraries, shared libraries, and dynamically loaded (Shared) libraries.
Static and dynamic linking are two processes of collecting and combining multiple object files in order to create a single executable. Linking can be performed at both compile time, when the source code is translated into machine code and load time, when the program is loaded into memory and executed by the loader, and even at run time.
Static Libraries
Static libraries are simply a collection of ordinary object files.This is a library of object code which is linked with, and becomes part of the application.The representation of static libraries conventionally, end with the “.a” suffix.This collection is created using the ar (archiver) program.
Advantages of Creating a Static Library :
- Static libraries permit users to link to programs without having to recompile its code, saving recompilation time.
- Static libraries are often useful for developers if they wish to permit programmers to link to their library, but don’t want to give the library source code.
Steps to Create Static Library :
1. Create a C file that contains functions in your library.
// Filename: lib.c #include <stdio.h> void library_fun(void) { printf("This function called from a static library"); }
2. Create a header file for the library
// Filename: lib.h void library_fun(void);
3. Compile library files.
gcc -c lib.c
4. Create static library. This step is to bundle multiple object files in one static library . The output of this step is static library.
ar rcs lib_mylib.a lib.o
Check man page of ar for more details or go to this link : ar
5. Now our static library is ready to use. At this point we could just copy mylib.a somewhere else to use it. For demo purposes, let us keep the library in the current directory.
Let us create a sample program that uses above created static library.
1. Create a C file with main function
// filename: sample.c
#include "lib.h"
void main()
{
library_fun();
}
2. Compile the sample program.
gcc -c sample.c
3. Link the compiled driver program to the static library. Note that -L. is used to tell that the static library is in current folder .
gcc -o sample sample.o -L. -l_mylib
4. Run the sample program.
./sample
This function called from a static library