Let's C Static Libraries
What are the static libraries
Mon Jul 15 2019 - 2 min read
A library in simple words is a file containing one or more object files. A static library is a collection of object files that are linked into the program once the linking phase in compilation is executing.
Why use libraries
Libraries are useful for developers because once everything is bundled into the application, you would not have to worry that the client have the right library on their system.
Also it adds speed to the process, since library code is connected at compile time, the executable has no dependencies on the library at run time so you don’t have to carry along a copy of the library that is being used.
How to create a static library
You can create a static library using a program called ar
, for archiver, an example using this command could be
ar -rc libpersonal.a *.o
This command creates a static library named libpersonal.a and puts copies of the object files on the current directory in it. The ‘r’ flag tells ‘ar’ to replace older object files in the library with the new object files and the ‘c’ flag tells it to create the library if it doesn’t already exist.
You could use ‘ranlib’ to re-generate the indexes.
How to use the statics libraries
After the static library is created, it has to be added to the list of object file names given to the linker, using the ‘-l’ flag.
gcc main.c -L. -lpersonal -o alpha
Note that it is omitted the ‘lib’ prefix and the ‘.a’ suffix when mentioning the library on the link command. The linker attaches these parts back to the name of the library to create a name of a file to look for. The ‘-L’ flag tells the linker that libraries might be found in the given directory, in this case is the working directory.
As you can see from these post, the static libraries are useful for our c programs and make our life easier, you just have to practice start creating your own libraries, so have fun!