C静态库、动态库

First Post:

Last Update:

Word Count:
227

Read Time:
1 min

C library

静态库

动态库

隐式调用

显示调用

实现.so文件的动态加载与自定义init函数和fini函数

files

1
2
3
4
5
.
├── lib
│   └── lib.c
├── main.c
├── makefile

lib/libc.c

1
2
3
4
5
#include <stdio.h>

void run() {
printf("load ok!\n");
}

main.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <unistd.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>

void my_init(void) __attribute__((constructor));// 告诉gcc把这个函数扔到init_section
void my_fini(void) __attribute__((destructor)); // 告诉gcc把这个函数扔到fini_section

void my_init(void) {
printf("init ...\n");
}
void my_fini(void) {
printf("fini ...\n");
}

int main(void) {
void *dl;
void *fun_run;
void (*run)();
//(void (*)())fun_run;


dl = dlopen("lib/lib.so", RTLD_LAZY);

if(dl == NULL) {
printf("open fail!\n");
exit(-1);
}

run = (void (*)()) dlsym(dl, "run");
run();

dlclose(dl);

return 0;
}

makefile

1
2
3
4
5
6
7
8
9
10
11
TARGET := p1
TARGET_LIB := lib.so
TOTAL :=


$(TARGET) : main.c $(TARGET_LIB)
gcc main.c -o $(TARGET) -fPIC -rdynamic -ldl


$(TARGET_LIB) : lib/lib.c
gcc lib/lib.c -o lib/$(TARGET_LIB) -shared -fPIC -rdynamic

输入make进行编译

运行如下:

1
2
3
4
./p1
init ...
load ok!
fini ...
打赏点小钱
支付宝 | Alipay
微信 | WeChat