实现一个简单的DLL动态链接库提供调用

在书上看到将c++类打包成DLL提供调用,自己也写了个很简单的程序。(VC++6.0的集成开发平台)

 
实现一个DLL动态链接库,先创建一个“Win32 Dynamic-Link Library”工程,工程名为“MathDLL”。选择创建一个“空”的工程。
 
编写头文件:SimpleMath.h 代码如下:
#ifndef _SimpleMath_Include
#define _SimpleMath_Include
 
class SimpleMath
{
    public:
        int _declspec(dllexport) Add(int a, int b);
        int _declspec(dllexport) Reduce(int a, int b);
};
 
#endif
 
在编写如下的SimpleMath.cpp文件:
#include "SimpleMath.h"
 
int SimpleMath::Add(int a, int b)
{
    return a+b;
}
 
int SimpleMath::Reduce(int a, int b)
{
    return a-b;
}
 
执行“Build”构建菜单,将在MathDLL\Debug目录下生成MathDLL.lib和MathDLL.dll两个文件。
现在在创建一个控制台程序来调用MathDLL.dll中两个类成员函数(Add 、Reduce)。
 
创建一个“Win32 Console Application”工程,工程名为“TestDLL”,选择创建一个“空”工程。
#include <stdio.h>
#include "..\MathClass\SimpleMath.h"
 
void main()
{
SimpleMath *result = new SimpleMath();
printf("10+20的值为:%d\n",result->Add(10,20));
printf("30-10的值为:%d\n",result->Reduce(30,10));
}
 
注意:要调用MathDLL.dll动态链接库,还要执行“工程->设置”在“连接”中输入MathDLL.lib文件的路径:..\MathDLL\Debug\MathDLL.lib。
 
在这里我运行的时候显示计算机丢失MathDLL.dll文件,原因是因为找不到“MathDLL.dll动态库文件“。只需把刚刚生成的MathDLL.lib文件拷贝到当前应用程序目录中就可以了。
原文地址:https://www.cnblogs.com/0YHT0/p/2474439.html