VS2013创建并使用DLL

VS2013创建并使用DLL

1.DLL文件

DLL(Dynamic Link Library)文件为动态链接库文件,又称“应用程序拓展”,是软件文件类型。在Windows中,许多应用程序并不是一个完整的可执行文件,它们被分割成一些相对独立的动态链接库,即DLL文件,放置于系统中。当我们执行某一个程序时,相应的DLL文件就会被调用。一个应用程序可使用多个DLL文件,一个DLL文件也可能被不同的应用程序使用,这样的DLL文件被称为共享DLL文件

2.创建DLL项目

创建win32应用控制台程序,取名为mydll,点击DLL选项。


新建goods.h 和goods.cpp 文件

goods.h

[cpp]  view plain  copy
  1. #pragma once  
  2.   
  3. #ifdef MYDLL_EXPORTS    
  4. #define MYDLL_API __declspec(dllexport)    
  5. #else    
  6. #define MYDLL_API __declspec(dllimport)    
  7. #endif   
  8.   
  9. #include <iostream>  
  10. #include <string>  
  11.   
  12. using namespace std;  
  13.   
  14. class MYDLL_API GOODS  
  15. {  
  16. public:  
  17.     GOODS::GOODS();  
  18.     GOODS::~GOODS();  
  19.   
  20.     int setname(string name);  
  21.   
  22.     int setnum(int num);  
  23.   
  24.     int setperunit(int perunit);  
  25.   
  26.     int printinfo();  
  27.   
  28.     int getcost();  
  29.   
  30. private:  
  31.     string m_name;  
  32.     int m_num;  
  33.     int m_perunit;  
  34. };  
goods.cpp

[cpp]  view plain  copy
  1. #include "goods.h"  
  2.   
  3. GOODS::GOODS()  
  4. {}  
  5.   
  6. GOODS::~GOODS()  
  7. {}  
  8.   
  9. int GOODS::setname(string name)  
  10. {  
  11.     m_name = name;  
  12.   
  13.     return 0;  
  14. }  
  15.   
  16. int GOODS::setnum(int num)  
  17. {  
  18.     m_num = num;  
  19.     return 0;  
  20. }  
  21.   
  22. int GOODS::setperunit(int perunit)  
  23. {  
  24.     m_perunit =perunit;  
  25.     return 0;  
  26. }  
  27.   
  28. int GOODS::printinfo()  
  29. {  
  30.     cout <<"name: " << m_name << endl;  
  31.     cout << "num: " << m_num << endl;  
  32.     cout << "perunit: " << m_perunit << endl;  
  33.   
  34.     return 0;  
  35. }  
  36.   
  37. int GOODS::getcost()  
  38. {   
  39.     int cost = m_num*m_perunit;  
  40.     return cost;  
  41. }  

项目源文件下添加.def文件。添加方法:添加—新建项—代码—模块定义文件。

最后生成解决方案,编译成功后可以在debug文件夹下发现mydll.dll和mydll.lib文件。
3.调用DLL项目

新建一个win32控制台的空项目,取名usemydll,然后引用dll步骤如下:

1.项目->属性->配置属性->VC++ 目录-> 在“包含目录”里添加头文件goods.h所在的目录 

2.项目->属性->配置属性->VC++ 目录-> 在“库目录”里添加头文件mydll.lib所在的目录 

3.项目->属性->配置属性->链接器->输入-> 在“附加依赖项”里添加“mydll.lib”

4.将dll项目下的debug文件中的math.dll复制到当前项目的debug文件夹中

新建添加main.cpp文件

main.cpp

[cpp]  view plain  copy
  1. #include "goods.h"  
  2.   
  3. int main()  
  4. {  
  5.     GOODS book;  
  6.   
  7.     book.setname("book");  
  8.   
  9.     book.setnum(2);  
  10.   
  11.     book.setperunit(10);  
  12.   
  13.     book.printinfo();  
  14.   
  15.     cout << "cost: "<<book.getcost() << endl;  
  16.   
  17.     return 0;  
  18. }