Blog move, original address: Learning dl Library in https://langzi989.github.io/2017/10/16/Unix/
In Linux, static link library and dynamic link library are two ways of code sharing between processes. Linux provides system calls to load and process dynamic connection libraries in the < dlfnc. H > library, which is very convenient to use. The specific usage is as follows:
Function description in dlfcn Library
The dlfcn library mainly includes four functions:
#include <dlfcn.h> void* dlopen(const char*, int flag); char* dlerror(); void* dlsym(void* handler, char* symbol); int dlclose(void* handler);
- dlopen: open a dynamic connection library, and return a handler of type void *, and flag is the open mode. There are two optional modes
- RTLD ﹣ lazy postpone decision, and solve the symbol when necessary
- RTLD? Now immediately decides to release all undecided symbols before returning.
- dlerror: returns the error of dl operation. If no error occurs, NUlL will be returned. Otherwise, the error information will be printed
- dlsym: find the symbol symbol in the dynamic link library and return the address of the symbol
- dlclose: close DLL handle
Using examples
Dynamic link library cal.cpp
//cal.cpp extern "C" { int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int mul(int a, int b) { return a * b; } int div(int a, int b) { return a / b; } }
Generate dynamic link library libcal.so
g++ -shared -fPIC cal.cpp libcal.so
//main.cpp #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> #define LIB_LIBRARY_PATH_1 "./libcal.so" typedef int (*CAC_FUNC)(int ,int); int main() { void* handler = NULL; char* error = NULL; CAC_FUNC cac_func = NULL; handler = dlopen(LIB_LIBRARY_PATH_1, RTLD_LAZY); if (!handler) { fprintf(stderr, "err:%s\n", dlerror()); exit(1); } dlerror(); //Here is the corresponding function address, *(void **) (&cac_func) = dlsym(handler, "add"); if ((error = dlerror()) != NULL) { fprintf(stderr, "err:%s", error); exit(1); } printf("add:%d\n", cac_func(1,2)); cac_func = (CAC_FUNC)dlsym(handler, "sub"); printf("sub:%d\n", cac_func(1,2)); cac_func = (CAC_FUNC)dlsym(handler, "mul"); printf("mul:%d\n", cac_func(1,2)); cac_func = (CAC_FUNC)dlsym(handler, "div"); printf("div:%d\n", cac_func(1,2)); dlclose(handler); return 0; }
Compile function main:
g++ main.cpp -rdynamic -ldl
Execution result:
add:3 sub:-1 mul:2 div:0
Pay attention to problems
In particular, if you use C + + to compile a dynamic link library, you must add extern "C" to the symbol you need to use, otherwise there will be a problem that the symbol cannot be found. undefined symbol