Static Libraries vs Dynamic Libraries
Libraries, why use them? In programming, libraries are collections of functions that may be used over and over. This eliminates the task of continuously rewriting them, thus saving time and effort.
What are Static Libraries? Static libraries are libraries that exist only within one’s current program. They are read into the executable at compile time, thus rendering them inert and modifiable after one’s code is compiled. Static libraries have the advantage of being more reliable, because they are cooked into the executable.
What are Dynamic Libraries? Dynamic libraries are very similar to static libraries, however, instead of being compiled into the executable, they exist as a file separate from the executable. This makes them editable at any point, even after the executable is compiled. However, the fact that makes dynamic libraries so readily editable also tends to make them less reliable, because of file corruption or user errors. These errors can very easily be passed into the executable resulting in errors.
How do we Create a Dynamic Library? Using Linux and GCC as the compiler: inside the directory that contains your c files. copy and paste this code:
gcc *.c -c -fPIC
The above code will generate an object file (*.o) for every source file (*.c)you have in the directory. If you want to target a specific file(s) replace the *.c with the files you want to use.
The second line of code to copy into your terminal:
gcc *.o -shared -o libmyfile.so
It is important that your output file have the lib prefix to it. You may otherwise name it whatever suits your needs. *.o simply gathers every file with the .o extension, and uses it for compilation. Again, you may specify the .o files you want to use by listing them, replacing the *.o. The -shared flag designates the library as a dynamic library. Finally, you may export the directory path for use on a Linux system by a quick copy and paste of:
How to use a Dynamic Library? When compiling with gcc, you may export your code as follows, including as many other flags as necessary, but these are the essentials:
gcc -L my_c_file.c -lmy_library_name -o my_output_file
It is worth noting that -l lets the compiler know that you have a file named “lib_my_library_name.so”, and it lives in the current directory, as we have noted my using -L. The executable file named by using -o is “my_output_file”.
The above is a very simplified and extremely narrow use-case, but the idea is there. Hopefully this has helped you on your journey.