3 动态库与静态库之类篇
3.1 素材(文件)
#pragma once
class Test{
public:
Test();
~Test();
void Func(int i);
};
#include <iostream>
#include "test.h"
using namespace std;
Test::Test(){cout << __func__ << endl;}
Test::~Test(){cout << __func__ << endl;}
void Test::Func(int i){
cout << __func__ << " i:" << i << endl;
}
#include <iostream>
#include "test.h"
using namespace std;
int main(){
Test t;
t.Func(100);
}
3.2 静态库的创建和使用
3.2.1 创建
(1)编译源文件
g++ -c -o test.o test.cpp
(2)生成静态库
ar -rcs libtest.a test.o
3.2.2 使用
(1)链接静态库
g++ -o main main.cpp -L. -ltest
或者
g++ -o main main.cpp ./libtest.a
注意:库一定要放在命令行的末尾
(2)测试
./main
(3)结果
Test
Func i:100
~Test
3.3 共享库的制作
3.3.1 创建
(1)编译目标文件
g++ -c -fPIC test.cpp -o test.o
(2)生成动态库
g++ -shared test.o -o libtest.so
可以合并为
g++ -shared -fPIC -o libtest.so test.cpp
3.3.2 使用
(1)生成可执行文件
g++ -o main main.cpp -L. -ltest
或者
g++ -o main main.cpp ./libtest.so
注意:库一定要放在命令行的末尾
(2)测试
指定动态链接库位置
export LD_LIBRARY_PATH=动态链接库位置
(3)执行
./main
(4)结果
Test
Func i:100
~Test
3.4 动态链接库的制作
类的动态链接库是利用多态性动态加载类,只能用于C++调用,不能用于C。
具体实现步骤如下:
(1)定义一个抽象类,提供纯虚函数接口。
(2)具体实现类继承抽象类。
(3)提供抽象类对象的创建和销毁的接口。
3.4.1 创建
#pragma once
class ITest{
public:
virtual void Func(int i) = 0;
virtual ~ITest(){}
};
class Test : public ITest{
public:
Test();
~Test();
void Func(int i);
};
extern "C" {
ITest* create(void);
void destroy(ITest *p);
typedef ITest* create_t(void); // create factory
typedef void destory_t(ITest*); // destory
}
#include <iostream>
#include "test.h"
using namespace std;
Test::Test(){
cout << __func__ << "()" << endl;
}
Test::~Test(){
cout << __func__ << "()" << endl;
}
void Test::Func(int i){
cout << __func__ << "(" << i << ")" << endl;
}
ITest* create(void){
return new Test;
}
void destroy(ITest *p){
if(NULL != p){
delete p;
}
}
#include <iostream>
#include <cstdlib>
#include <dlfcn.h>
#include "test.h"
using namespace std;
int main(){
void *so_handle = dlopen("./libtest.so", RTLD_LAZY);
if (!so_handle) {
cerr << "Error: load so failed." << endl;
exit(-1);
}
create_t *create = (create_t*) dlsym(so_handle, "create");
char *err = dlerror();
if (NULL != err) {
cerr << err;
exit(-1);
}
ITest *pt = create();
pt->Func(100);
destory_t *destroy = (destory_t*) dlsym(so_handle, "destroy");
err = dlerror();
if (NULL != err) {
cerr << err;
exit(-1);
}
destroy(pt);
pt = NULL;
dlclose(so_handle);
return 0;
}
3.4.2 使用
(1)编译动态加载库
g++ -shared -fPIC -o libtest.so test.cpp
(2)编译主程序
g++ -o main -ldl main.cpp
(3)测试
./main
(4)结果
Test()
Func(100)
~Test()
3.5 总结
静态库、共享库与动态库编译链接使用比较