Linux动态库的使用方式
时间: 2024-02-12 14:31:40 浏览: 30
Linux动态库一般采用共享库的方式进行使用,其使用方式如下:
1. 编写动态库代码并编译生成动态库文件,一般为.so文件。
2. 在需要使用该动态库的程序中,通过头文件声明动态库函数。
3. 在编译该程序时需要告知编译器动态库文件的位置和名称,一般使用-l选项或者-L选项和-l选项组合使用。其中,-L选项指定动态库文件所在的目录,-l选项指定动态库文件的名称。
4. 在程序运行时,动态库文件会被加载到程序的地址空间中,程序就可以调用动态库中的函数了。
下面是一个简单的示例程序:
动态库代码:
```
//mylib.c
#include <stdio.h>
void say_hello(){
printf("Hello World!\n");
}
```
编译动态库:
```
gcc -shared -fPIC mylib.c -o libmylib.so
```
使用动态库的程序代码:
```
//main.c
#include <stdio.h>
#include <dlfcn.h>
int main(){
void *handle;
void (*say_hello)();
char *error;
handle = dlopen("./libmylib.so", RTLD_LAZY);
if(!handle){
fputs(dlerror(), stderr);
exit(1);
}
say_hello = dlsym(handle, "say_hello");
if((error = dlerror()) != NULL){
fputs(error, stderr);
exit(1);
}
say_hello();
dlclose(handle);
return 0;
}
```
编译程序:
```
gcc main.c -L. -lmylib -o main
```
运行程序:
```
./main
```
输出结果:
```
Hello World!
```