Dynamic Libraries in C

The main reason to create a library in C is to have all functions organized, be more efficient as programmer and to have everything in one place, and with that comes the question: “What should i use? A dynamic library or a static library”.
To answer that question, we first need to understand the difference between these two; in static libraries the linker makes a copy of all the functions from the library to the executable, in dynamic libraries this is not necessary, it’s a difference in data usage, data corruption and how difficult is the code to handle.
How Dynamic Libraries are created.
In order to create a dynamic library we’ll use the gcc comand using -c to generate all the .o files from the .c files and then -fPIC to make the code position independent, after that you’ll see a ton of .o files from all your .c files.
gcc -c -fPIC *.c
Now we’re going to put everything together in a single library, to do it as a Dynamic Library we’ll use the -shared flag. (With the -o you can specify the name of the .o file).
gcc -shared -o libholberton.so *.o
Congrats! You have your library created, to check if it created correctly you can use this command:
nm -D libholberton.so
How To Use Your Library
Great, at this point you should already have your library ready to go, in order to make it work you need to add the location of your library to your enviromental values so other files can locate it and use their functions.
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
Now we compile
gcc -L . main.c -l lib -o a
This is a bit of a different compilation command, we use -L to tell the program where the library is plus the . which tells that it’s in the current directory and the -l tells the program to look for a library.
And that’s it! Thank you for reading!.