Static libraries in C — Why are they important?
Static libraries are collections of object files that are linked together when a file gets compiled into an executable file.
A function can be defined as a blocks of code that are reusable in a program, and we use them to saves time, removing the need to rewrite code multiple times. Libraries, like functions also save time in that they make functions reusable in multiple programs.
Libraries are very important in C because this language supports only the basic features that it needs. For example, C doesn’t contain input-output (I/O) functions to read from the keyboard and write to the screen. Anything that extends outside the essentials must be coded by a programmer.
If the chunk of code is useful to multiple different programs, it’s recommended to put into a library to make it easily reusable, this will saves you valuable time and your code will be reduced.
Libraries or portions of libraries depending on your header files, get added to the executable file during the linking phase of the compilation process.
When you hit the return button that has gcc main.c typed in the terminal, any functions that are included in your header file (if their system header files) gets added into the executable file, along with your main.c source code.
To create a static library using GCC we need to compile our library code into an object file so we tell GCC to do this using the -c flag, for example:
gcc -c *.c
c means to create an intermediary object file, rather than an executable. The -c compiler option is needed to suppress linking. Without this option, the compiler generates an error because the library does not contain a main program.
Then, having all our .o files created, with go to next step which is to create the library, with the help of ar command, which is used to create, modify and extract the files from the archives:
ar rc test_lib.a *.o
This creates the static library test_lib.a
r means to insert with replacement and c means to create a new archive.
Finally we need to index our library using the ranlib command to generates an index to the contents of an archive and it will be stored in the archive. The index lists each symbol defined by a member of an archive which is simply relocatable object file. You may use nm to list all of this index.
When we are creating statics libraries another usefull flags for gcc are -l and -L. The first one links with a library file, while the second one looks in directory for library files