Computer Systems Practical - Part 3: Dynamic Linking

Abstract

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.

  1. 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.
  2. Save disk space. The code and data of the shared library are shared by all executable object files that refer to the shared library.
  3. 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.

Difference between static link and dynamic link

Objects Linker The period
Static Static linker (ld on Linux) Compilation
Dynamic Dynamic linker (ld-linux-x86-64.so.2) Loading or runtime

How to generate shared libraries

Generate shared libraries

1
2
3
4
5
6
7
8
// test.cpp
int g_val_1 = 1;
int g_val_2 = 2;

void func() {
g_val_1 *= 2;
g_val_2 *= 2;
}
1
2
3
4
5
6
7
8
9
10
// main.cpp
extern int g_val_1;
extern int g_val_2;

void func();

int main() {
func();
return 0;
}
1
2
g++ -shared -fpic -o libtest.so test.cpp		
g++ -o main main.cpp ./libtest.so
  • -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