静态库和共享库(动态库)的编译链接
文章目录
- 静态库
- 代码
- 文件
- 过程
- 动态库
- 代码
- 过程
静态库
代码
gcc -c test.c -o test.o //生成目标文件
ar crs libtest.a test.o //生成静态库
gcc main.c -L./ -ltest -o main_test //链接静态库
文件
静态文件test.c
#include <stdio.h>void Hello(const char* arg)
{printf("Hello %s\n",arg);
}
源文件main.c
#include <stdio.h>extern void Hello(const char * arg);int main()
{Hello("world");return 0;
}
过程
step1:生成目标文件
gcc -c test.c -o test.o
step2:编译(生成)静态库
ar crs libtest.a test.o
ls
libtest.a main.c test.c test.o
step3:链接静态库
gcc main.c -L./ -ltest -o main_test
ls
main_test libtest.a main.c test.c test.o
运行
./main_test
动态库
代码
1.创建动态库
gcc -fPIC -Wall -c test.c //编译为位置无关代码(PIC)
gcc -shared -o libtest.so test.o //创建共享库
2.编译链接主程序
# 方法1 指定路径
gcc main.c -o app -L./ -lmytest //生成可执行文件app,但找不到动态库
# 方法2 通过环境变量
pwd
export LIBRARY_PATH=$LIBRARY_PATH:(动态库所在的路径) //相当于-L的作用
3.设置系统寻找动态库的路径
# 方法1:指定路径
cp libtest.so /usr/lib/ //系统会从这里找
./app# 方法2:环境变量
pwd //复制共享库的路径
sudo vim /etc/ld.so.conf //通过在/etc/ld.so.conf文件中添加共享库的路径来实现
sudo ldconfig
./app
过程
ls
main.c test.c
step1:生成目标文件
gcc -fPIC -Wall -c test.c -o test.o
ls
main.c test.c test.o
step2:创建共享库
gcc -shared -o libtest.so test.o
ls
libtest.so main.c test.c test.o
step3:链接到可执行文件
gcc main.c -o app -L./ -lmytest
ls
app libtest.so main.c test.c test.o
step4:设置路径
把共享库libtest.so复制到/usr/lib/下
或
在/etc/ld.so.conf文件中添加libtest.so所在的路径(pwd)