Static vs Dynamic libraries
Libraries are a very important tool in programming because they let the programmer re-use the code he/she created, so when a programmer knows that a code should be re-used in future programs, is useful to create a library with this code.
A library in C language is a tool that is responsible for containing object files of C programs (programs that containing C functions like strcpy or atoi) and makes it easier for the compiler in the linking process, optimizing times of compilation.
How to create a dynamic library in (Linux)
To create a dynamic library is necessary to use gcc compiler with some options. First, we need to have the object files of the C programs that will be part of the library. To do so we use the gcc compiler with two options: -c for creating the object files and -fPIC for the files to be "Position Independent Code", so the code can be in any part of memory.
gcc *.c -c -fPIC
With this command, we will compile but not link the files, and with the *.c all the .c files in the current directory will be compiled and generate a .o file for every c file. It should look like this in your terminal:
Then, we use gcc with the option -shared to specify that a dynamic library is been created:
领英推荐
gcc *.o -shared -o liball.so
'liball.so' can be replaced with the name you want your library to have. The result should look like this:
With our library created, now we can modify the environment variable LD_LIBRARY_PATH to add the path of the new library for the compiler to be able to find it.
export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH
And that's it. Now you can use your own library this way: use the gcc compiler when compiling your new program, with the option -L so the compiler search for the library, and the -l option to tell the compiler the name of the library, like this:
gcc -L new_program.c -lall -o test_code
With this, the new_program.c file will be compiled and linked with the library liball.so (the all after the -l flag is completed with the lib prefix and .so extension).