Static Libraries in C
A Library is a set of functions. Usually a developer can create a new library, to reuse all its typical functions to be called from some other program. It’s like a program, only it doesn’t have a main () function.
Kind of libraries
Static Libraries. They are linked when compiling, they remain “inside” the final executable. In Linux they have the extension .a.
Dynamic Libraries. They are linked when executing, the operating system must find them when executing the program.
Advantages and Disadvantages of Static Libraries
- Static libraries resist vulnerability because it lives inside the executable file.
- The speed at run-time occurs faster because its object code (binary) is in the executable file. Thus, calls made to the functions get executed quicker.
- Changes made to the files and program require relinking and recompilation.
- File size is much larger.
How to create static libraries in C
- Create a C file that contains functions in your library.
- Create a header file for the library, for example you can create
$ vim mylib.h
- Compile library files.
$ gcc -c mylib.c -o mylib.o
- 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 rc mylib.a mylib.o
archiveand it is used to create the static library. All the files ending in
“.o”will be added to the
mylib.a libraryand they are the object files in this case.
-rc flagwill do two things: replace and create a new library if it does not exist already.
- The next step is indexing, to do that, we type:
- 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.
How to use static libraries in C
Finally to use the static library, type the following command:
gcc main.c -L -l<filename>
-L flag accesses the
linker so the libraries can be found in the given directory. Also, it also searches for other locations where the compiler looks for system libraries.