本文以my_sum求和函数为例
生成DLL
创建DLL项目工程: file -> new project -> Installed -> Visual C++ -> Windows Desktop -> Dynamic-Link Library -> 工程名用默认的Dll1
编辑DLL工程:添加Dll1.h头文件,在里面输入如下代码
#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
DLL_API int my_sum(int a, int b);
在Dll1.cpp中添加如下代码
#include "stdafx.h"
#include "Dll1.h"
int my_sum(int a, int b)
{
return a + b;
}
编译输出DLL:Build -> Build Solution,即可在工程目录的Debug文件夹下看到多个文件。其中Dll1.dll和Dll1.lib是后面要的文件。
使用DLL
新建项目:file -> new project -> Installed -> Visual C++ -> Windows Desktop -> Windows Console Application -> 输入项目名Dll1_test
复制dll文件:复制Dll1.dll、Dll1.lib和Dll1.h到项目文件夹的子目录Dll1_test下。
编辑测试代码:在Dll1_test.cpp中添加如下代码:
#include "stdafx.h"
#include "Dll1.h"
int main()
{
int a = 1, b = 2;
printf("%d + %d = %d\n", a, b, my_sum(a, b));
return 0;
}
添加lib到资源文件
方法1: Solution Explorer -> Dll1_test -> Resource Files[右键] -> Add -> Existing Item -> 选中Dll1.lib -> Add
方法2:Solution Explorer -> Dll1_test[右键] -> Configuration Properties -> Linker -> Input -> Additional Dependencies -> Edit -> 添加Dll1.lib
编译运行Dll1_test
快捷键:CTRL+F5
或者 Build -> Build Solution,然后 Debug-> Start Without Debugging
如果成功,控制台第一行输出如下
1+2=3