Dynamic/shared library

Salah Besbes
2 min readDec 14, 2020

A library is a collection of pre-compiled pieces of code that can be reused in a program. Libraries simplify life for programmers, they provide reusable functions, routines, classes, data structures and so on
which they can be reused in a programs.

The library is indexed and it’s linked into the program during the linking phase of compilation.

in case of dynamic library :

  • Only the address of all functions contained in the library are included in the executable file, in other word the executable file is gonna add a fraction of code (addresses).
  • Dynamic linking links the libraries at the run-time ( he last step of the compilation process. After the program is placed in the memory )
  • executable file contain only functions that are called from the library
  • The library lives outside the executable file
  • Multiple Programs can use a dynamic library without the need to copy it into the program it self

in case of static library:

  • All the library is hard coded (copied) into the executable file, it’s locked into the executable program.
  • If we modify the library we have to recompile the program. Because the version of the library contained into the exec file is out of date, to update it after we have to recompile the hole program.

To create a dynamic library:

gcc -fPIC -c *.c

  • -fPIC : instructs the compiler to generate position independent code, because the location of the library in memory will vary between programs.
  • -c : create object files

gcc -shared libNmae.so -o *.o

  • -shared will detect the library Name starting by the prefix ‘ lib ’ and extension ‘ .so ’
  • -o will create the library

Before you can use a dynamic library as a dependent library, the library and its header files must be installed on your computer. The standard locations for header files are ~/include, /usr/local/include and /usr/include.

And the standard locations for dynamic libraries are ~/lib, /usr/local/lib, and /usr/lib.

You may also place the newlib.so file at a nonstandard location in your file system, but you must add that location to one of these environment variables:

  • LD_LIBRARY_PATH
  • DYLD_LIBRARY_PATH
  • DYLD_FALLBACK_LIBRARY_PATH
export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH

--

--