STATIC LIBRARIES IN C
WHY USE LIBRARIES?
A library is a set of functions. It is like a program. It contains typical functions to be called from some other program or library to perform a common task and any developer can create a new library. For example, the gcc compiler automatically links the standard C library to its programs.
Static libraries are object files that are then combined with another object to form a final executable.
This way we can use them whenever we want. The huge advantages of this are:
HOW THEY WORK?
To use a library, we must have:
The headers are the files with .h extension that contain the ''declarations'' (also called ''prototypes'') of the functions (A function that is ''defined'' inside a header is called an ''inline'' function).?
They are invoked through the ''preprocessor directive'' (so called because it is done at the ''preprocessing'' stage of the compiler) #include, which performs a simple substitution. The compiler must be able to locate the headers.
HOW TO CREATE THEM?
To create a static library it is necessary to follow the steps below:
2. To convert all .c files to objetc (.o) files at once, this script is applied at the prompt (with or without flags):
If you list the files they will look like this:
领英推荐
3. Now, there are all the object files to be added to your library. Then, to create a library and add those files, you must use this simple script in the directory where all the files are (.o).
You can apply this "ar -t" script to see what is inside your library.
4. Finally, as physical libraries you have to index or sort the information you have there.?ranlib generates an index of the contents of a file and stores it in the file. The index lists each symbol defined by a member of a file that is a relocatable object file. A file with such an index speeds up linking to the library and allows routines in the library to call each other regardless of their location in the file. This is a good practice because it will make the linking step faster.?
HOW TO USE THEM?
Now that a static library is created and it allows us to use it by invoking it as part of the linking process when creating an executable program. You can do this easily, just use the flag when you apply the gcc compilation code, like this:
There is an important detail to take into account. The libraries must be placed in such a way that the highest level library is first and the lowest level library is last.
Static linking is useful, but it has two main disadvantages: