A shared library, also know as a shareable object files, can be loaded by a dynamic linker to any memory address during the loading or runtime, and linked to a program in memory.
The link process can be carried out during the loading period or run time. Therefore, after the shared library is updated, it is not necessary to do the static library, and the executable object file must be explicitly relinked.
Save disk space. The code and data of the shared library are shared by all executable object files that refer to the shared library.
Save memory space. A copy of the code of the shared library in memory is shared by all processes the refer to the shared library.
-shared - linker option - indicating that the linker generates a shared library.
-fpic - compiler option - indicating that the compiler generates location-independent code.
-fno-pic - compiler option - not to generate position-independent code.
1 2
ldd main # view shared libraries needed readelf -p .interp main # View the .interp section
Runtime loading and link sharing library
Function
Prototype
Parameters
Return
Open the shared library
void *dlopen(const char *filename, int flag)
- Specfify the path of the shared library - Specify the flag of opening the shared library. Common option: RTLD_LAZY, RTLD_NOW, RTLD_GLOBAL, RTLD_LOCAL.
Return a handle pointer to the shared library. Otherwise, return NULL.
Close the shared library
int dlclose(void *handle)
- A handle pointer to the shared library
Successful return 0, otherwise return -1
Find symbol
void *dlsym(void *handle, char *symbol)
- A handle pointer to a shared library - The name of the symbol definition to be found
Successful return a pointer to the symbol, otherwise return NULL