#include <stdio.h>
int sum(int a, int b)
{
int temp = a + b;
printf("helloworld %d\n", temp);
return temp;
}
- gcc -c -fPIC test.c
- gcc -shared -fPIC -o libtest.so test.o
#include <dlfcn.h>
#include <stdio.h>
typedef int (*hello_t)(int, int);
int main()
{
void *lib = dlopen("test.so", RTLD_LAZY);
hello_t hello = (hello_t)dlsym(lib, "hello");
hello(3, 5);
dlcose(lib);
}
gcc -o test dlopen.c -ldl
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.
- gcc dlopen.c -L/opt/code -ltest -o test -ldl
动态库在链接时需要指明动态库的位置 -L, 以及库的名称 -l。 编译器会在库名称前加lib,后加.so,-ltest会变为libtest.so。
链接时指明环境变量,export LD_LIBRARY_PATH=$LD_LIBRARAY_PATH:. ,指明库位置在当前目录下。
函数接口
void *dlopen(const char *file, int mode);
功能:打开指定的动态链接库文件,并将它读入内存,返回一个句柄给调用进程
参数:mode
-RTLD_LAZY:暂缓决定,等有需要时在解析出符号。
-RTLD_NOW:立即决定,返回前解出所有符号。
-RTLD_GLOBAL:动态库中定义的符号可被其后打开的其他库重定位。
-RTLD_LOCAL:与RTLD_GLOBAL相反
void *dlsym(void *handle, const char *name);
功能:根据动态链接库操作句柄与符号,返回符号对应的地址,可以是函数或者变量。
参数:
-handle: dlopen返回的动态链接库句柄。
-name: 符号名称,可为函数名或变量名。
int dlclose(void *handle)
功能: 关闭指定句柄的动态链接库,只有当此动态链接库的使用计数为0时才会被真正卸载。