Compilation and Application of Dynamic Link Library Dll

foreword

This article is mainly to help you write and use DLL in a simple way. There are many explanations on the Internet about what a DLL is, so I won’t talk nonsense here.

Realize the function

1. DLL export function
2. DLL export class

1. Generate DLL

1. Create a new C++ empty project project. The project name is myDll here. 2.
Create myDll.cpp and myDll.h files . export data, function, class or class member function


#pragma once
//导出函数
__declspec(dllexport) int Add(int a, int b);  //加法函数
__declspec(dllexport) int Sub(int a, int b);  //减法函数

//导出类
class __declspec(dllexport) CMyDll
{
    
    
public:
 int Mul(int a, int b); //乘法函数
 int Div(int a, int b); //除法函数
 };

myDll.cpp file

#include "myDll.h"
/*函数实现*/
int Add(int a, int b)
{
    
    
 return a + b;
}
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;
}

4. Generate dll dynamic link library file
1) Configure project properties as shown in the figure below
insert image description here2) Right-click on the project name and select Generate to generate dll files
insert image description here5. Generate lib static link library files
1) Configure project properties as shown in the figure below
insert image description here
2) Right-click on the project name , select Generate to generate the lib file
insert image description here

2. Using DLLs

1. Create a new C++ empty project project, here the project name is useDll
2. Create a useDll.cpp file
3. Take the dll, lib files and myDll.h files generated by the myDll project and place them in the useDll project
insert image description here
4 , Add the myDll.h file to the project of useDll
insert image description here
5. The code of useDll.cpp is as follows

#include <iostream>
#include "./include/myDll.h"
#pragma comment (lib, "./dll/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::getchar();
 }

6. Right-click the project name of useDll and select Generate to generate the exe file.
The running results are as follows:
insert image description here

Guess you like

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