C Dynamic libraries

Daniel Ortega Chaux
3 min readMay 3, 2021

What is a library?

A library is where we can keep items that we might call later for our program, which will actually save us a lot of time. There are S and dynamic libraries.

Differences between Static and Dynamic libraries:

Main differences between Static and Dynamic libraries

Static libraries when we call a function in the main, during the compilation process the compiler will link the code you wrote in the main with the code of the function that is in the library and it will be added at the end of the link.

  • Is a compiled file which contains the symbols that the main program needs to operate, such as functions and variables.
  • When we call a function in the main, the compiler will link that code wrote in main with the code of the function that is in the library, and it will be added.

Dynamic libraries make the same compile process as static libraries when you compile your code with the code of the function called, the difference is that at the end of the linker, it will be added not the code of the function you called but the address where the function is located in the library.

  • The process of compilation is still the same of the static libraries until it gets to the linker, at that point it will be added not the code of the function you called but the address where the function is located in the library.

How to create a Dynamic library in Unix? How it works?

  1. First, we need to compile and assembly our “.c” files. To do it we use the following line command:

gcc -c -fPIC *.c

  • -c-> Compiles and assemble, do not link.
  • -fPIC-> Flag Position Independent Code means that the generated machine code is not dependent on being located at a specific address in order to work.
  • *.c-> Compile all the .c files
  • gcc -c *.c-> will compile all the .c files and create a “.o” extension file which mean object code.

Example:

Convert .c files in .o files (object files)

2. Now we can compile with the “-shared” flag to create the dynamic library:

gcc -shared -o my_lib.so My_file.o

  • -o->Is used to give a name to the executable file
  • My_file.o->The last file has to be the “.o”
  • This command creates a dynamic library called My_library.so and puts copies of the object files My_file.o in it.

How to use libraries?

When a program use a dynamic library the system needs to find them so the compiler will search for the dynamic version which is “.so”. It will search for it in the $LD_LIBRARY_PATH variable paths.

$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/user/dir_lib

  • $LD_LIBRARY_PATH->This environment variable is used to indicate in which directory it have to search for it.

How to use them:

Check out my blog about static libraries where I also explain how to use them!

--

--