静态库
准备文件
test.cpp
#include "stdio.h"
#include "test.h"
int printhello(int a,int b)
{
printf("hello");
return a+b;
}
test.h
int printhello(int a,int b);
main.cpp
#include "test.h"
#include "stdio.h"
int main(void)
{
int b;
b = printhello(1,2);
printf("\r\n b = %d \r\n", b);
return 0;
}
编译
- 生成test的输出文件
gcc -c test.cpp
编译完后生成test.o
- 编译为静态库
ar -cr libabc.a test.o
编译完后生成 libabc.a
此处libabc.a为静态库文件
3. 编译main函数
gcc -o main main.cpp -L. libabc.a
编译完后生成main
- 运行
./main
此时哪怕删的只剩下main 一个文件也能运行
共享库
准备文件
同上
编译
- 生成test的输出文件
gcc -fPIC -c test.cpp
编译完后生成test.o
2.编译动态库文件
gcc -shared -o libabc.so test.o
编译完后生成libabc.so
此处libabc.so为静态库文件
3. 编译main函数
gcc -o main main.cpp -L. libabc.so
编译完后生成main
- 运行
./main
发现报错
./main: error while loading shared libraries: libabc.so: cannot open shared object file: No such file or directory
原因是共享库必须在环境变量中,将共享库文件libabc.so 复制到/lib或者/usr/lib下,或者将共享库文件所在位置添加到环境变量中再运行
export LD_LIBRARY_PATH=“.”
再运行,正常!
本文详细介绍了如何创建和使用静态库与共享库。通过实例展示了编译过程,包括生成静态库libabc.a和动态库libabc.so。在使用共享库时,需要注意将其路径添加到环境变量中才能正常运行。
1101

被折叠的 条评论
为什么被折叠?



