欢迎光临
我们一直在努力

C++ DLL动态库怎么创建与调用

本篇内容介绍了“C++ DLL动态库怎么创建与调用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

1、创建库工程

2、添加头文件

ClassDll.h

// 宏定义 防止.h文件重复编译
#ifndef _DLLCLASS_H
#define _DLLCLASS_H

// dll库文件 定义 宏(DLLCLASS_EXPORTS) 使用 _declspec(dllexport)
// 使用dll库文件时 _declspec(dllimport)(不定义宏就行)
#ifdef DLLCLASS_EXPORTS
#define EXT_CLASS  _declspec(dllexport)
#else
#define EXT_CLASS  _declspec(dllimport)
#endif

// 定义库文件的 类(导出或导入)
class EXT_CLASS CMath 
{
public:
	// 定义函数
	int Add(int item1, int item2);
	int Sub(int item1, int item2);
};

#endif

3、添加cpp文件

ClassDll.cpp

// 定义 宏(DLLCLASS_EXPORTS) 头文件类
// 使用 _declspec(dllexport) 导出
#define DLLCLASS_EXPORTS

#include "ClassDll.h"

// 实现类函数
int CMath::Add(int item1, int item2) 
{
	return item1 + item2;
}

int CMath::Sub(int item1, int item2) 
{
	return item1 - item2;
}

4、编译dll工程

生成文件

5、创建调用工程

普通工程、多字节项目

6、调用工程 添加cpp文件

UseClassdll.cpp

#include <iostream>
using namespace std;

// 导入头文件 库类 使用 _declspec(dllimport) 导出类
#include "../ClassDll/ClassDll.h"

// 隐式调用dll 加载库文件
#pragma comment(lib, "../Debug/ClassDll.lib")

// 运行时  dll文件与exe文件在一个文件夹中
int main() {
	// 定义 dll库中的类
	CMath math;

	// 调用函数
	int sum = math.Add(5, 6);
	int sub = math.Sub(5, 6);

	// 打印结果
	cout << "sum=" << sum << " sub=" << sub << endl;
	system("pause");
	return 0;
}

“C++ DLL动态库怎么创建与调用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注云搜网网站,小编将为大家输出更多高质量的实用文章!

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。