C static libraries
What is a library?
A library or library is a program without autonomy that must be used by another program, but there are executable that can function as a library and as a stand-alone program, so where does a library start and where does a program start?
In C this differentiation gives us the entry point and the exported functions.
The entry point:
It is where any executable will begin to run, it is the main function.
The exported functions:
They are other points of entry to an executable code (the explanation is more technical and complex, it could even require a different response).
Therefore we can conclude that:
- When an executable has an entry point but does not export functions, it is a program.
- When an executable has several exported functions but lacks an entry point, it is a library.
- When an executable has both, it can be both.
To use a library with these characteristics, you must link your binary with your binary. As an analogy we could think of the engine of a car: you can use the engine in several types of car to make them circulate but the engine itself is nothing without the rest of the vehicle’s elements.
Why we should use them?
- They contain the specifications of different features already built and usable that we can add to our program, such as reading from the keyboard or displaying something on the screen among many others.
- We save a lot of things, imagine for example that every time we need to read by keyboard, we must then create a function that does (something really complex), to have libraries in C, we can make use of a variety of functions that will facilitate our lives and increase the modularity of our codes.
In conclusion
The libraries are files (not always external) that allow us to carry out different tasks without worrying about how they are done but simply understand how to use them. The libraries in C ++ allow to make our programs more modular and reusable, making it easier to create programs with quite complex functionalities in a few lines of code.
How works?
- The header file of the library is included.
- Library functions and variables are used.
- The library is linked together with the executable program.
These steps also apply when the object modules do not combine to form a library. Including the header file and linking the object modules is the basis for separate compilation in C
Example
Let’s go see an example. First we need to create a header file like the next one.
Now, we should implement the behavior of us function in a c file
So, we created two files, and that files are the library, but we should use the library. In this case, we are going to create another file called main.c that make a call to the library.
Now you should have three files, mylib.c, mylib.h and main.c
. If you don't have it, copy the files before go to other part.
Now we are able to execute our program with ./message "goodbye, i hope and you like it"
