1使用MSVC封装库文件
1.1配置
.h文件需要配置,导入导出以及平台设置
#ifdef CLASS_LIBRAR
#define CLASS_EXPORT __declspec(dllexport)
#else
#define CLASS_EXPORT __declspec(dllimport)
#endif
.h文件配置
#ifdef __cplusplus
extern "C" { //only need to export C interface if used by C++ source code
#endif
__declspec(dllimport) void MyCFunc();
__declspec(dllimport) void AnotherCFunc();
#ifdef __cplusplus
}
#endif
.cpp文件函数正常编写
2在Visual Studio 2022中成功封装并调用库的案例
2.1 封装教程
第一步 创建动态库项目
创建新项目——》选择动态库模板
第二步 删除自带文件
创建成功后,删除自带的头文件和源文件
第三步 配置属性
选中项目右键属性——》选择C/C++——》选择“预编译头”—>预编译头,设置成不使用
第四步 添加预处理器定义
添加预处理器定义(DLL_BUILD),后面编写头文件用得上
第五步 创建自己的代码
.h文件
#pragma once
//dll部署操作
#ifdef DLL_BUILD
//标识为导出操作
#define DLL_API _declspec(dllexport)
#else
//标识为引入操作
#define DLL_API _declspec(dllimport)
#endif
#include <vector>
using namespace std;
const int null = 11111111;
//Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
//编译器识别
#ifdef __cplusplus
extern "C" {
#endif
//通过数组转换成对应的二叉树
DLL_API TreeNode* generateBinaryTree(vector<int>& nodes);
//测试函数是否封装成功 1:成功
DLL_API int success();
#ifdef __cplusplus
}
#endif // __cplusplus
.cpp文件
#include "CreateBiTree.h"
#include <queue>
//null:11111111
TreeNode* generateBinaryTree(vector<int>& nodes)
{
int len = nodes.size();
if (len == 0)return NULL;
queue<TreeNode*> q;
TreeNode* root = new TreeNode(nodes[0]);
q.push(root);
int index = 1;
while (!q.empty()&&index<len) //填充孩子
{
TreeNode* node = q.front();
q.pop();
if (index < len) //添加左孩子
{
int leftVal = nodes[index++];
if (leftVal != null)
{
TreeNode* leftChild = new TreeNode(leftVal);
node->left = leftChild;
q.push(leftChild);
}
}
if (index < len) //添加左孩子
{
int rightVal = nodes[index++];
if (rightVal != null)
{
TreeNode* rightChild = new TreeNode(rightVal);
node->right = rightChild;
q.push(rightChild);
}
}
}
return root;
}
int success()
{
return 1;
}
第六步 点击生成
(库项目不可以运行哦)
最后成功后,会生成.dll文件和.lib文件,记得使用它时,把头文件也带走哦
2.2 调用dll教程
第一步 创建空项目
创建一个空项目,并创建一个main函数用于测试。
在项目下创建两个文件夹include和bin,分别用于存放.h文件和dll及lib文件
第二步 配置属性
配置exe的输出目录,注意c++项目的根路径相对于**.vcxproj**文件
第三步 引用头文件
就是封装dll使用的头文件所在目录:CreateBinaryTree.h
第四步 引用库目录
就是 dll所在目录CreateBinaryTree.dll
第五步 引用lib文件
在连接器—》输入-----》附加依赖项—》双击编辑添加CreateBinaryTree.lib
第六步 添加头文件,即可调用封装的函数了
输出结果: