C static libraries
Why use libraries :
A library is helpful because it allows programmers to skip writing some complicated but frequently needed procedures. The documentation in a library allows the programmer to understand how the procedure works without reading the code
How they work :
We frequently use libraries to fill in the holes in our code so we don't have to reinvent the wheel...
Just in case you need a refresher, here's what you need to know: Libraries are simply files that contain a set of functions.
The difference between a static library and a dynamic (shared) library is the first thing you should understand. They're all useful in different ways.
Static libraries are better for quickly getting a library up and running, but they have disadvantages as well.
How to create them :
When a C program is compiled, the compiler generates object code. After generating the object code, the compiler also invokes linker. One of the main tasks for linker is to make code of library functions (eg printf(), scanf(), sqrt(), ..etc) available to your program. A linker can accomplish this task in two ways, by copying the code of library function to your object code, or by making some arrangements so that the complete code of library functions is not copied, but made available at run-time.
Steps to create a static library Let us create and use a Static Library in UNIX or UNIX like OS.
1. Create a C file that contains functions in your library.
We have created only one file for simplicity. We can also create multiple files in a library.
2. Create a header file for the library
3. Compile library files.
gcc -c lib_mylib.c -o lib_mylib.o
4. Create static library. This step is to bundle multiple object files in one static library (see ar for details). The output of this step is static library.
ar rcs lib_mylib.a lib_mylib.o
5. Now our static library is ready to use. At this point we could just copy lib_mylib.a somewhere else to use it. For demo purposes, let us keep the library in the current directory.
Let us create a driver program that uses above created static library.
1. Create a C file with main function
2. Compile the driver program.
gcc -c driver.c -o driver.o
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 (See this for details of -L and -l options).
gcc -o driver driver.o -L. -l_mylib
4. Run the driver program
./driver fun() called from a static library
Thank you for taking the time to read this article I hope it helps you ^^