How to create Static libraries in C
You might have multiple function that you created in the past and you think it’ll good to re-use them, but to do this you might need to re-write them in your file or use other way but not really relevant. So Today in this article i will show you, what is a static libraries and why use them, how to create one and how to use them, but it exists also an another type of library called dynamic library but i’ll not cover this subject today, only the static library.
So what is a static library and why use them? A static library is an archive file, that looks like a collection of files, who contains multiple object code of your function files that you want to re-use (if you don’t know what is a object code, check my previous article of compilation gcc) and are indexed (see after). The static library will be given to the linker process in compilation GCC (we will see that after how to) and will help the linker(see my previous article about compilation) to go faster because all the file you needed is in ONE file and are indexed, indexed object code means that all the symbols (function in your function_file.o, global variables..) of each function are visible, so the linker can link more easier with your file.c. Use library will help you a lot, you will not have to re-add them in your file but just to call them.
Now, how to create one ? First, you will need to create a Header file that contain all prototypes of all your functions that will be in the library, like this:
So now, after this article you will just have to add the header file that you created, at the top of your file.c to use function in your library, like this :
So, now you’ll have to compile all the functions you want in your library BUT stop before the end of the process of compilation, so before the linker part, you will just need to create the object code (as i said before) of all your functions, like this :
Now that you have all your object code files, we will create our library with the command “ar” who create an archive file, like this:
And you need to add one more command which is :
Congrats, your library is created but wait it’s not finished yet, i have to show other things to do :)
To list all your object code in the library use this command :
To list all the files indexed in your library(you will see all functions/global variables.. in your function object code), use this command :
Now, the last part of this article, i’ll show you how to use your beautiful library : )
You just have to add the library in you gcc command to the linker process with this command :
The “-L” parameter tell to the linker that the library is in your current folder and the “-l” tell to the linker the header file name.
You just have now, to compile like i show and add the header file at the top of your file and just call the function you need.
Now, you have finished, you have a beautiful library that will help you a lot :).
Stay tuned.