需要的环境
新建DLL项目
#pragma once
#ifdef JayLIBDLL
#define JAYAPI _declspec(dllexport)
#else
#define JAYAPI _declspec(dllimport)
#endif
double JAYAPI f1();
double JAYAPI f2(double);
#include "pch.h"
#define JayLIBDLL
#include "jay.h"
double JAYAPI f1()
{
return 1;
}
double JAYAPI f2(double a)
{
return a * a;
}
新建调用项目
- 首先将.lib、.h文件拷贝到当前项目目录下
- 添加main.cpp
#include "pch.h"
#include <iostream>
using namespace std;
#include "jay.h"
#pragma comment(lib,"Dll1.lib")
int main()
{
cout << f2(1) << endl;
}
- 编译,然后将之前生成的.dll文件拷贝到编译后生成.exe的文件夹下,执行。
多个类生成DLL
- 基于上面的DLL生成项目之上,添加新的模块,例如selfTrainingDll.h(这段代码来自互联网)
#pragma once
#ifdef TESTLIBDLL
#define DLL_TRAINING_API _declspec(dllexport)
#else
#define DLL_TRAINING_API _declspec(dllimport)
#endif
class DLL_TRAINING_API arithmetic_operation
{
public:
double Add(double a, double b);
double Sub(double a, double b);
double Multi(double a, double b);
double Div(double a, double b);
};
int DLL_TRAINING_API export333();
#include "pch.h"
#include <iostream>
#define TESTLIBDLL
#include "selfTrainingDll.h"
using namespace std;
double DLL_TRAINING_API arithmetic_operation::Add(double a, double b) {
return a + b;
}
double DLL_TRAINING_API arithmetic_operation::Sub(double a, double b) {
return a - b;
}
double DLL_TRAINING_API arithmetic_operation::Multi(double a, double b) {
return a * b;
}
double DLL_TRAINING_API arithmetic_operation::Div(double a, double b) {
return a / b;
}
int DLL_TRAINING_API export333() {
return 333;
}
- 一样的编译,替换一下新生成的.lib、.h以及.dll,同时修改调用项目下的main.cpp
#include "pch.h"
#include <iostream>
using namespace std;
#include "selfTrainingDll.h"
#include "jay.h"
#pragma comment(lib,"Dll1.lib")
int main()
{
arithmetic_operation ao;
cout << ao.Add(1, 2) << endl;
cout << ao.Sub(2, 1) << endl;
cout << ao.Multi(2, 1) << endl;
cout << ao.Div(6, 4) << endl;
cout << export333() << endl;
cout << f2(1) << endl;
cout << "Hello World!\n";
}