Dynamic or shared libraries in C
in this blog, i’m going to explain what is dynamic library,difference between dynamic and static libraries, how they works. first why is dynamic linking
Dynamic linking
Dynamic linking means the use of shared libraries. Shared libraries usually end with .so
(short for "shared object").
Dynamic libraries
dynamic or shared library is a collection of functions compiled and stored in an executable with purpose of being linked by other programs at run-time.
Static linking
When your application links against a static library, the library’s code becomes part of the resulting executable. This is performed only once at linking time, and these static libraries usually end with a .a
extension.
you can read all about static libraries in c here.
1. How to create the dynamic library
- First you need create all function that you want in you dinamic libraries
- To start we need to create the object files first with command
gcc -fPIC -c *.c
we created the object files with the -fPIC
flag. This flag stands for Position Independent Code, a characteristic required by shared libraries.
- in this step we’ll create a dynamic libraries usin this command
gcc -shared -Wl,-soname,whatevername.so -o whatevername.so *.o
The -shared
key tells the compiler to produce a shared object which can then be linked with other objects to form an executable. -Wl
flag passes an options to linker with following format -Wl,options
, in case of our example it sets the name of library, as it will be passed to the linker.
2. How to use a dynamic library
One way around this is to add the repository folder to the environment variable LD_LIBRARY_PATH
to tell the linker where to look for the correct version. In this case, the right version is in this folder, so you can export it:
$ LD_LIBRARY_PATH=$(pwd):$LD_LIBRARY_PATH
$ export LD_LIBRARY_PATH
Now the dynamic linker knows where to find the library, and the application can be executed. You can ldd
to invoke the dynamic linker, which inspects the application's dependencies and loads them into memory. The memory address is shown after the object path:
ldd my_app
yourlibrarie.so.1 (0x00007ffd385f7000)
libmy_shared.so => /home/cristian/folder/youlibraries.so (0x00007f3fad401000)
libc.so.6 => /lib64/libc.so.6 (0x00007f3fad21d000)
/lib64/ld-linux-x86-64.so.2 (0x00007f3fad408000)
o find out which linker is invoked, you can use file
:
file my_app
my_app: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=26c677b771122b4c99f0fd9ee001e6c743550fa6, for GNU/Linux 3.2.0, not stripped
3. Work with dynamic libraries
we need to find out what functions a library has, we should use the nm
command:
nm yourlibrarie.so