一、创建静态链接库
//.h文件中
class Calculator
{
private:
float x;
float y;
CString str;
public:
Calculator(float x, float y);
~Calculator();
void setParam(float x, float y);
void add();
void sub();
void mul();
void div();
};
//.cpp文件
#include "stdafx.h"
#include "MyLib.h"
Calculator::Calculator(float x, float y)
{
this->x = x;
this->y = y;
this->str = L"";
}
Calculator::~Calculator()
{
this->str = L"";
}
void Calculator::setParam(float x, float y)
{
this->x = x;
this->y = y;
}
void Calculator::add()
{
str.Format(L"%.3f",x+y);
MessageBox(NULL,str,L"计算结果",MB_OK|MB_ICONINFORMATION);
}
void Calculator::sub()
{
str.Format(L"%.3f",x-y);
MessageBox(NULL,str,L"计算结果",MB_OK|MB_ICONINFORMATION);
}
void Calculator::mul()
{
str.Format(L"%.3f",x*y);
MessageBox(NULL,str,L"计算结果",MB_OK|MB_ICONINFORMATION);
}
void Calculator::div()
{
if(y != 0)
{
str.Format(L"%.3f",x/y);
MessageBox(NULL,str,L"计算结果",MB_OK|MB_ICONINFORMATION);
}
else
{
MessageBox(NULL,L"除数不能为0",L"提示",MB_OK|MB_ICONERROR);
}
}
编译,生成.lib文件。(项目属性根据应用情况设置)
把MyLib.h、MFC静态链接库.lib文件拷贝到项目中,就能使用静态链接库了。
二、新建一个对话框程序测试。(项目属性)
//.h文件中
#include "INC\\MyLib.h"
#pragma comment(lib, "LIB\\MFC静态链接库.lib")
//.cpp文件中(四个按钮的事件处理程序)
void C调用静态链接库Dlg::OnBnClickedBtnAdd()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData();
m_calc.setParam(m_num1,m_num2);
m_calc.add();
}
void C调用静态链接库Dlg::OnBnClickedBtnSub()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData();
m_calc.setParam(m_num1,m_num2);
m_calc.sub();
}
void C调用静态链接库Dlg::OnBnClickedBtnMul()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData();
m_calc.setParam(m_num1,m_num2);
m_calc.mul();
}
void C调用静态链接库Dlg::OnBnClickedBtnDiv()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData();
m_calc.setParam(m_num1,m_num2);
m_calc.div();
}