2020-12-02

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值