将C++代码编译成动态库,供另一个C++程序调用。
写了个简单的demo,主要是看看流程。
首先,目标文件代码,test.h test.cpp
test.h:
#include <iostream>
using namespace std;
class Demo
{
public:
Demo( int x);
~Demo(){};
void print_data();
private:
int a;
};
test.cpp:
#include "test.h"
Demo::Demo(int x):a(x)
{
}
void Demo::print_data()
{
cout<<a<<endl;
}
编译成动态库:
g++ -c test.cpp -fPIC -o test.o
g++ -shared -o libtest.so test.o
这样就可以生成动态库libtest.so
接下来写个test2.cpp调用这个动态库
test2.cpp:
#include <iostream>
#include "test.h"
int main()
{
Demo demo(999);
demo.print_data();
return 0;
}
编译:
g++ -o test2 test2.cpp -L /root/tmp -ltest
结果:
[root@one tmp]# ./test2
999
至此,动态库的生成与调用,一个简单的demo就完成了。
参考文档: