linux下动态库制作的实例
参考博客:
https://www.cnblogs.com/skynet/p/3372855.html
https://blog.csdn.net/qq_37596943/article/details/82721042
https://www.cnblogs.com/fengliu-/p/10216723.html
先编写头文件和源代码源代码文件
DynamicMath.h
#pragma once
class DynamicMath
{
public:
static double add (double a,double b);
static double sub (double a,double b);
static double mul (double a,double b);
static double div (double a,double b);
void print();
};
DynamicMath.cpp
#include <iostream>
#include "DynamicMath.h"
double DynamicMath::add(double a,double b)
{
return a + b;
}
double DynamicMath::sub(double a,double b)
{
return a - b;
}
double DynamicMath::mul(double a,double b)
{
return a * b;
}
double DynamicMath::div(double a,double b)
{
return a / b;
}
void DynamicMath::print()
{
std::cout << "this is DynamicMath lib" << std::endl;
}
生成动态库文件
g++ -fPIC -c DynamicMath.cpp -o DynamicMath.o
g++ -shared DynamicMath.o -o libdynmath.so
也可以两句写在一起
g++ -fPIC -shared DynamicMath.cpp -o libdynmath.so
然后写测试程序
#include "DynamicMath.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
double a = 10;
double b = 2;
cout << "a + b = " << DynamicMath::add(a, b) << endl;
cout << "a - b = " << DynamicMath::sub(a, b) << endl;
cout << "a * b = " << DynamicMath::mul(a, b) << endl;
cout << "a / b = " << DynamicMath::div(a, b) << endl;
DynamicMath dyn;
dyn.print();
return 0;
}
编译测试程序
g++ test.cpp -o test -L. -ldynmath
运行测试程序(LD_LIBRARY_PATH:指定动态库位置)
LD_LIBRARY_PATH=. ./test