vs2013创建动态链接库

来源:互联网 发布:阿里云邮箱企业版pc端 编辑:程序博客网 时间:2024/05/17 09:36

最近开发一个小项目,需要创建和使用动态链接库,参照网上的方法,自己实践了一下。

主要参考这篇文章:http://blog.csdn.net/lushuner/article/details/23947407


创建dll文件:

1.新建项目,win32,win32项目,输入项目名称,例如:MakeDll。

2.确定,下一步:

3.菜单栏选择项目——添加新项,来创建头文件MakeDll.h。


在MakeDll.h中输入以下例子代码:

[cpp] view plain copy
  1. #define DLL_API __declspec(dllexport)  
  2. #include<iostream>  
  3. using namespace std;  
  4.   
  5. DLL_API int add(int a, int b);  
  6. class DLL_API Point  
  7. {  
  8. private:  
  9.     float x, y;  
  10. public:  
  11.     Point();  
  12.     void SetPoint(float a, float b);  
  13.     void Display();  
  14. };  

4.创建MakeDll.cpp来实现MakeDll.h中的函数和类;


在MakeDll.cpp中需要包含MakeDll.h头文件

步骤:右击项目——属性——配置属性——VC++目录——可执行文件目录,在项目中找到MakeDll.h所在目录,包含以下就可以了

在MakeDll.cpp中的代码如下:

[cpp] view plain copy
  1. #include “MakeDll.h  
  2. DLL_API int add(int a, int b)  
  3. {  
  4.     return a + b;  
  5. }  
  6. Point::Point()  
  7. {  
  8.     x = 0.0f;  
  9.     y = 0.0f;  
  10. }  
  11. void Point::SetPoint(float x, float y)  
  12. {  
  13.     this->x = x;  
  14.     this->y = y;  
  15. }  
  16. void Point::Display()  
  17. {  
  18.     cout << "x= " << x << endl;  
  19.     cout << "y= " << y << endl;  
  20. }  

5.菜单栏——生成——生成解决方案。

此时在MakeDll项目所在目录下的Debug目录下的文件有MakeDll.dll和MakeDll.lib了。生成动态链接库文件OK。


调用DLL

1.新建项目——win32控制台应用程序,项目名称:UseDll,确定——下一步,勾上空项目。(若选win32,则会出现

error LNK2019: 无法解析的外部符号 _WinMain@16,该符号在函数 ___tmainCRTStartup 中被引用 MSVC”错误

2.将第一个项目中生成的MakeDll.dll、MakeDll.lib和MakeDll.h复制到  UseDll\UseDll目录下,将MakeDll.h包含在头文件中

3.在项目中新建一个UseDll.cpp,代码如下:

[cpp] view plain copy
  1. #include  “MakeDll.h”  
  2. #define DLL_API __declspec(dllimport)  
  3. #pragma comment(lib,"MakeDll.lib")  
  4. int main()  
  5. {  
  6.     Point p1, p2;  
  7.     p2.SetPoint(5.6f, 7.8f);  
  8.     p1.Display();  
  9.     p2.Display();  
  10.     cout << "5+6 = " << add(5, 6) << endl;  
  11.     return 0;  
  12. }  
OK,运行成功。