Compilation and use of dynamic link library Dll - simple version

提示:以下是本篇文章正文内容,下面案例可供参考

1. Generate DLL

1. Create a project to generate a DLL, as shown in the figure below.
insert image description here
2. Click Next and set as shown in the figure below. If the generated DLL is for the MFC application, please check the MFC check box.
insert image description here
3. After clicking Finish, the generated project is as follows. The system will generate examples of exported classes, exported variables, and exported functions for us. We can follow the example to add the corresponding exported types.
insert image description here4. Add the function of "addition, subtraction, multiplication and division" on the basis of this example, the code is as follows.
myDll.h file

#ifdef MYDLL_EXPORTS
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif
// 此类是从 myDll.dll 导出的
//导出类
class MYDLL_API CmyDll {
    
    
public:
 CmyDll(void);
 // TODO:  在此添加您的方法。
 int Mul(int a, int b);
 int Div(int a, int b);
};

//导出变量
extern MYDLL_API int nmyDll;

//导出函数
MYDLL_API int fnmyDll(void);
MYDLL_API int Add(int a, int b);
MYDLL_API int Sub(int a, int b);

myDll.cpp file

#include "stdafx.h"
#include "myDll.h"
// 这是导出变量的一个示例
MYDLL_API int nmyDll=0;

// 这是导出函数的一个示例。
MYDLL_API int fnmyDll(void)
{
    
    
    return 42;
}
// 这是已导出类的构造函数。
// 有关类定义的信息,请参阅 myDll.h
CmyDll::CmyDll()
{
    
    
    return;
}
/*函数实现*/
MYDLL_API int Add(int a, int b)
{
    
    
 return a + b;
}
MYDLL_API int Sub(int a, int b)
{
    
    
 return a - b;
}
int CmyDll::Mul(int a, int b)
{
    
    
 return a * b;
}
int CmyDll::Div(int a, int b)
{
    
    
 return a / b;
}

5. Right-click the project name and select Generate to generate dll files and lib files, and the generated files are in the Debug file.
insert image description here

2. Using DLLs

1. Create a new project
Create a new project useDll under the original solution, and use the DLL in this project.
insert image description here
2. Create the useDll.cpp file under the useDll project, the code is as follows.

#include <iostream>
#include "../myDll/myDll.h"

#pragma comment (lib, "../Debug/myDll.lib")

int main()
{
    
    
 int a = 6, b = 2;
 //使用导出函数
 std::cout << "a + b = " << Add(a, b) << std::endl;
 std::cout << "a - b = " << Sub(a, b) << std::endl;
  //使用导出类
 CmyDll myDll;
 std::cout << "a * b = " << myDll.Mul(a, b) << std::endl;
 std::cout << "a / b = " << myDll.Div(a, b) << std::endl;
  //使用导出变量
 std::cout << "nmyDll = " << nmyDll << std::endl;
  std::getchar();
}
 

3. Right-click the project name and set useDll as the startup project. After compiling, the running results are as follows.
insert image description here

Guess you like

Origin blog.csdn.net/NICHUN12345/article/details/127342198