我们知道C++ DLL动态链接库里面定义了很多的函数与方法,由于它的容积小,可移植性,在很多桌面应用程序里面都有广泛的使用,那么我们该如何使用C或C++来自定义DLL动态链接库呢?
第一步:我们在自己的Visual Studio里面点击菜单:File---New---Project---Visual C++---Win32 Project---DLL即可新建一个DLL动态链接库的项目,结构如图所示:

小编新建的是项目是Mydll,开始是没有Mydll.h这个头文件的,需要自己创建一下header头文件。
第二步:例如小编要创建一个add的加法运算函数,则在Mydll.h中这样定义即可,使用extern关键字,代码如下:
#pragma once extern "C" _declspec(dllexport) int add(int a, int b);
第三步:在Mydll.cpp中实现我刚刚定义的add函数,引入Mydll.h头文件,代码如下:
// Mydll.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "Mydll.h"
int add(int a, int b)
{
return a + b;
}第四步:生成dll动态链接库,方法很简单,就是右键项目,然后Rebuild一下即可,生成之后我们的工程Debug目录下会生成这些dll文件,如图:

第五步:在别的地方使用C++定义的dll动态链接库,代码如下所示:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
typedef int(*AddFunc)(int , int );
long main()
{
//直接调用Mydll的前提是Mydll.dll文件必须放在工程目录的Debug目录下
HMODULE hDll2 = LoadLibrary(L"Mydll.dll");
if (hDll2 != NULL)
{
AddFunc add = (AddFunc)GetProcAddress(hDll2, "add");
if (add != NULL)
{
int result = add(1, 2);
cout << "结果:" << result << endl;
}
printf("\r\n");
system("pause");
}
return 0;
}上方的C++调用DLL动态链接库输出结果为:3