Static libraries in C programming
Libraries are a group of files that have pre-built functionalities that can be used by any executable file. The libraries contain variables and functions inside, and certain types of files that we can import or include in our program. These files could contain the specifications of different functionalities already built-in and ready to use, and this feature makes the programmers life easier, trust me.
Why use libraries
A C library is a group of object files packaged in one and only file, used as, again, an individual item in a linking phase of a program. Remember that in a gcc compile process for a C source program the linking phase is the final step made by the linker accepting input object files and libraries to produce the final executable program.
Libraries feature two advantages over files separates on the disk: less files and indexing for them and this enables considerably faster linking process an important fact to take in account.
How libraries work
In C there are two types of libraries: static and dynamic libraries and we will center on static libraries this time.
Static libraries
The key feature of a static library is that you need a copy of it for building the executable in the linking process. That .exe file will work in other systems without requiring any additional files.
How to create static libraries
We’re going to follow the steps required to create and modify a static library
- Create some C function programs
Create some .c programs, let’s say add.c and mul.c
2. Compile the Programs and Get Object Files
Using gcc with option -c will create the corresponding .o files
Now we have both the .c and .o files
3. Create the C Program Static Library using ar program
Let’s make a break and think. The static libraries are created by the program called ‘ar’ an abbreviation for ‘ archiver’ that can manipulate them in several ways: create, edit, modify…
Next thing to do is create the static library with the command ar, we will call it “libarith.a” with the add and mul objects files.
In the last command the ‘c’ flag tells ar to create the library if it doesn’t already exist. The ‘r’ flag tells it to replace older object files in the library, with the new object file.
4. Use ranlib command to index static libraries
Some systems do not us ‘ar’ as archiver and the programs that creates the libraries also take care of index. The program ‘ar’ and ‘ranlib’ work together and we gonna keep that way.
How Using A “C” Library In A Program
We just created our library libarith.a, now we gonna use it. At this point just two things left a header file and a main program.
Compile our main to generate and object program:
The option -L instructs the compiler to look in the current directory for library files.
And finally test main executable
Bibliography
· The Linux Programmer’s Toolbox By John Fusco
· https://www.sitesbay.com/cprogramming/c-compile-link-program