First of all, it’s better to understand why we need to use library in C (Linux)
The primary reason of it, is, using library will help you a lot, you will not have to re-write them in your file and make more and more doublons, with library you will just have to call functions you need in your program.
So now we know why use library, why use a dynamic library instead of a static one?
There is two ways of process with library, the linker will connect all the function.. at the last step of compilation (linker) needed to your program to run, it can do that in two ways, first one by copying all the code of library function needed to your object code OR make sure in other way to not copying all the function needed but made it available at run-time to your executable.
Dynamic libraries doesn’t require all the code to be copied into the object code as static libraries, it is done just by placing name of the library in the binary file, the linking happens when the program is run when both the binary file and the library are in memory. If changes append with files, no need to re-compile to have the changes with all the program that use this library. With static library we need to recompiled the program to have the changes.
- Much smaller because there is no copy of all functions needed in your executable, only exist in the memory.
- Faster because the library is linked at run-time and already in memory and no need to copying all the files, functions..
- No need to recompiled the program to have the changes.
How to create a dynamic library ? (Linux)
First of all you need to have all your files that you want in your future library, so make sure that there all in your current directory.
You will have to generate the object code of all the files you need, so to generate this object code, use this command :
gcc *.c -c -fPIC
(fPIC = Position Independent Code means that the generated machine code is not dependent on being located at a specific address in order to work)
Now that you have all your files transformed into object code, you need to generate your beautiful library !!
To generate your library, use this command :
gcc *.o -shared -o library_name.so
The extension of dynamic libraries are “.so”
Congrats, your library is created and are in the memory ready to use !
To list all the functions that you have in your library, use this command:
nm -D your_lib.so
How to use your library ? (linux)
You can now, call all the function that you added in your library, in all programs where you want to use these functions without re-copying it to use it BUT not exactly now.
To execute your program with the library, you just have to use this command :
gcc -Wall -pedantic -Werror -Wextra -L. your_program.c -name_lib -o name_executable
The “-L.” tells to the linker to search the library with “-name_lib” in the current directory.
To print all the shared object dependancies of your program , use this:
To export the library, use this command :