C Static Libraries : Collection of files
A library in C is a collection of files meant to be used by other programs.?
The library consists of two types of files, a header, the interface expressed in a .h file which contains prototypes of functions, and a function or implementation in a compiled *.c file (object file *.o).?
The libraries can be Static or Dynamic (also known as Shared). Static Libraries are linked to the executable file, in this case, an *.exe contains all routines for a program to run. On the other hand, Dynamic libraries are not part of the executable file because they are loaded at runtime, in this case, the *.exe file needs an external link or dynamic loader to access the library routines successfully.
The reason to use libraries is to simplify a code, splitting the source code into small units of related files, that can be managed separately by a unique file. Furthermore, libraries may call functions in other libraries to do various tasks.?
Static Library
A static library consists of one or more object files, these object files that have been compile are turned into a library as an archive by the ar archiver. The program takes files and stores them in a bigger file.?Then the linker copies the library to every program file that invokes the static library to get an executable file.
In Unix and Linux OS, the filename for the library usually starts with "lib" and ends with *.a and the object files with *.o . Microsoft Windows OS use a *.lib extension for libraries and an *.obj extension for object files.
Here is an example of how to create them:
领英推荐
gcc -Wall -Werror -Wextra -pedantic -c *.c
ar -rc libname.a *.o
ranlib libnambe.a
Keep in mind that a copy of the library becomes part of every executable that uses it,?to update the library, the entire executable needs to be replaced.
A Static Library must be included in the linking process with the flag -l to use the library in a program, without the prefix lib and sufix .a, as follows:
cc main.o -L. -lname -o programname.exe
Blog entry to describe static libraries in C and how to create them. Thanks for reading!