动态链接库
功能
写项目的时候需要头文件来声明函数,源文件来写函数具体实现,然后还得写一个main函数来使用前面声明的函数。而动态库则可以将源文件都打包成一个库,在链接的时候和main文件链接在一起,满足需求。
例子
头文件:so_test.h
//so_test.h:
#include<iostream>
void test_a();
void test_b();
void test_c();
三个源文件:test_a.cpp,test_b.cpp,test_c.cpp
//test_a.cpp:
#include "so_test.h"
#include<iostream>
using namespace std;
void test_a()
{
cout<<"this is in test_a..."<<endl;
}
//test_b.cpp
#include "so_test.h"
#include<iostream>
using namespace std;
void test_b()
{
cout<<"this is in test_b..."<<endl;
}
//test_c.cpp
#include "so_test.h"
#include<iostream>
using namespace std;
void test_c()
{
cout<<"this is in test_c..."<<endl;
}
主函数文件:test.cpp
#include"so_test.h"
int main()
{
test_a();
test_b();
test_c();
return 0;
}
目的:将三个源文件打包成动态库,并与主函数文件链接生成可执行文件。
实现
g++ test_a.cpp test_b.cpp test_c.cpp -fPIC -shared -o libsotest.so
//生成动态库
使用-fPIC能让一个库给多个主函数使用,而不是通过拷贝复制给其他函数使用。
使用-shared表示-o是生成动态库而不是可执行文件
g++ test.cpp -L. -lsotest -o test
//动态库与主函数链接
使用-L来指明动态库文件所在路径,-l指明动态库文件名(去掉lib和.so)-o生成可执行文件test。
然后运行./test
这里有可能会遇到找不到动态库文件的报错(程序运行时),相关解决办法网上很多,我采用临时解决办法
export LD_LIBRARY_PATH=/home/aotuman/c++_learning/dong_tai_ku_learning2
之后就可以运行了。