静态库
准备文件
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=“.”
再运行,正常!