1、打开Microsoft Visual Studio 2010,选择File->New->Project。
2、在New Project中选择Installed Templates->Visual C++->Win32。
3、选择Win32 Console Application,设置名称:simpledll,设置解决方案名:zdddll。
4、单击OK,在出现的Win32 Application Wizard的Overview对话框中点击Next。
5、在Application Settings中,选择Application type下的DLL。
6、勾选Additional options下的Empty project。
7、单击Finish创建项目。
二、向动态链接库添加类:
1、添加新类头文件。右键单击simpledll项目,Add->New Item,选择Header File(.h),设置名称为simpledll,单击Add。
2、添加新类源文件。右键单击simpledll项目,Add->New Item,选择C++ File(.cpp),设置名称为simpledll,单击Add。
3、为新类添加内容。内容如下:
头文件simpledll.h:
1 //------------------ simpledll.h ----------------
2 #pragma once;
3 //该宏完成在dll项目内部使用__declspec(dllexport)导出
4 //在dll项目外部使用时,用__declspec(dllimport)导入
5 //宏DLL_IMPLEMENT在simpledll.cpp中定义
6 #ifdef DLL_IMPLEMENT
7 #define DLL_API __declspec(dllexport)
8 #else
9 #define DLL_API __declspec(dllimport)
10 #endif
11 namespace ly
12 {
13 //导出类
14 class DLL_API SimpleDll
15 {
16 public:
17 SimpleDll();
18 ~SimpleDll();
19 int add(int x,int y);//简单方法
20 };
21 }
源文件simpledll.cpp:
1 //------------------ simpledll.cpp ----------------
2 //注意此处的宏定义需要写在#include "simpledll.h"之前
3 //以完成在dll项目内部使用__declspec(dllexport)导出
4 //在dll项目外部使用时,用__declspec(dllimport)导入
5 #define DLL_IMPLEMENT
6 #include"simpledll.h"
7 namespace ly
8 {
9 SimpleDll::SimpleDll()
10 {
11 }
12 SimpleDll::~SimpleDll()
13 {
14 }
15 intSimpleDll::add(int x,int y)
16 {
17 return x+y;
18 }
19 }
4、完成后点击Build->Build Solution,生成解决方案。可在~lydll\Debug下查看生成的simpledll.lib和simpledll.dll.文件。
三、创建引用动态链接库的应用程序:
1、选择File->New->Project。
2、在New Project中选择Installed Templates->Visual C++->Win32。
3、选择Win32 Console Application,设置名称:usesimpledll。选择Add to solution。
4、单击OK,在出现的Win32 Application Wizard的Overview对话框中点击Next。
5、在Application Settings中,选择Application type下的Console application。
6、取消Additional options下的Precompiled header,勾选Empty project。
7、单击Finish创建项目。
四、在控制台应用程序中使用类库的功能:
1、为控制台应用程序添加main.cpp。右键单击usesimpledll项目,Add->New Item,选择C++ File(.cpp),设置名称为main,单击Add。
2、为main.cpp添加内容。如下所示:
1 //------------------ main.cpp -------------------
2 #include"simpledll.h"
3 usingnamespace zdd;
4 #include
5 usingnamespace std;
6 int main(char argc,char**argv)
7 {
8 //
9 cout <<"----------------------"< 10 SimpleDll sd; 11 cout <<"sd.add: 3+5="<< sd.add(3,5)< 12 cout <<"sd.getConst(): "< 13 SimpleDll*psd =newSimpleDll; 14 cout <<"psd->add: 5+5="<< psd->add(5,5)< 15 cout <<"psd->getConst(): "< 16 cout <<"----------------------"< 17 cout <<"please press Enter exit."< 18 getchar(); 19 return0; 20 } 3、引用simpledll项目。右键单击usesimpledll项目,选择Properties->Common Properties->Framework and References。点击Add New Reference,选择simpledll项目,单击OK。 4、设置头文件路径。选择Properties->Configuration Properties->VC++ Directories。在Include Directories项添加$(SolutionDir)\simpledll\,选择应用,确定。 5、设置usesimpledll项目为活动项目。右键单击usesimpledll项目,选择Set up StartUp Project。 6、生成解决方案。Debug运行结果如下: