Shared libraries are reusable libraries which can be used by multiple applications at the same time. The advantages of shared libraries are
- Can be loaded at application start or on demand at run time.
- Can be upgraded separately and reloaded.
Only disadvantage compared to statically linked library is, there is an overhead for loading the library and resolving the symbols at run time.
In case of loading during application start, the loader will load the library into process virtual address space and resolve before the application is launched.
In case of loading dynamically the same can be achieved with the respective system library apis when in need..
Windows it will be a dynamically linked library(*.dll) and uses the same PE format as windows executable.
Linux it will be a shared object(*.so) and uses the ELF format as a normal linux executable.
In linux use the -shared gcc option to create a shared object. if your library name provided is abc.so, the linux linker will create it as libabc.so.
While statically linking, the option -labc should be provided to link with the same.
If you are using dynamic linking, you need to use dlopen(3) ,dlsym(3) and dlclose(3) apis to load, access the symbol and unload the library.
int main(int argc, char * argv)
int call_lib(int num);
int call_lib(int num)
printf(“passed value is %d\n”, num);
To compile the library code
gcc -shared -fPIC -o library.so library.c
To compile the application code
gcc -o sample -L /home/yogi/libs -lrary application.c
Running the executable
set first the library path
passed value is 3
Source: Working with Shared Libraries | Set 1 – GeeksforGeeks