-
创建共享库源文件
math.c
:int add(int a, int b) {return a + b; }
-
创建共享库头文件
math.h
:int add(int a, int b);
-
编译动态链接库:
gcc -shared -fPIC math.c -o libmath.so
-shared
:共享对象(shared object),是 Linux 下对动态库的另一种称谓-fPIC
:Position Independent Code,
-
编辑主程序源文件
main.c
:#include <stdio.h> #include "math.h"int main() {printf("add(1, 2) returned %d\n", add(1, 2)) }
-
编译主程序:
gcc main.c -lmath -L. -o main
-lmath
:-l
选项用来指定动态链接库,这里指定了math
库(前缀lib
和后缀.so
被省略)-L.
:-L
选项用来指定查找动态链接库的位置,这里指定了当前目录.
-
执行主程序:
LD_LIBRARY_PATH="$(pwd)" ./main
LD_LIBRARY_PATH
:指定运行程序时查找动态链接库的路径
参见:动态链接库(dll)是如何工作的?| 小红书