C++ Dll 库 的创建与使用方法记录

一、生成Dll,使用qt creator 工程,而且DLL 使用了QtCore 模块(具体看应用需要增加使用那些模块)

默认生成三个文件

复制代码
//libTest_global.h
#ifndef LIBTEST_GLOBAL_H
#define LIBTEST_GLOBAL_H

#include <QtCore/qglobal.h>

//qt 使用的 导入导出关键属性 
// LIBTEST_LIBRARY 是在pro 中定义

#if defined(LIBTEST_LIBRARY)
#  define LIBTEST_EXPORT Q_DECL_EXPORT 
#else
#  define LIBTEST_EXPORT Q_DECL_IMPORT
#endif

#endif // LIBTEST_GLOBAL_H

// 导出函数、类 的 头文件 libtest.h

#ifndef LIBTEST_H
#define LIBTEST_H

#include "LibTest_global.h"

/***************************************************************
*  @Copyright:  Copyright (c) 2024 LK. All rights reserved.
*  @FileName:   libtest.h
*  @Brief:      关于c++ 如何创建 dll 的例子
*  @Author:     HXJ
*  @Date:       2024-09-06
****************************************************************/

#ifdef __cplusplus
//第一种,直接导出类
//为了避免暴露实现细节,使用类似于D 指针的实现方式进行封装
class LibDirectImp;
class LIBTEST_EXPORT LibDirect
{
public:
    LibDirect();
    ~LibDirect();

    //外部可用的函数
    void PrintName();
private:
    LibDirectImp* m_imp;
};


//第二种, 导出虚基类,
//内部实现 一个子类
//提供一个创建函数,创建子类对象返回基类指针
class LIBTEST_EXPORT LibVirtualBase{

public:
    virtual void PrintName() = 0;
};

//导出创建函数 更好的是返回智能指针
//这个函数甚至可用使用 c风格导出
LIBTEST_EXPORT LibVirtualBase *CreatLib();

#endif

//c 风格函数导出

extern "C"
{
    LIBTEST_EXPORT void TestFun();
}


#endif // LIBTEST_H

// 具体实现

#include "libtest.h"
#include <QDebug>

#ifdef __cplusplus
class LibDirectImp{
public:
    LibDirectImp()
    {

    }

    //外部可用的函数
    void PrintName()
    {
        qDebug() << "LibDirect";
    }
};


LibDirect::LibDirect()
    :m_imp(new LibDirectImp())
{
}

LibDirect::~LibDirect()
{
    delete m_imp;
}

void LibDirect::PrintName()
{
    m_imp->PrintName();
}


//子类化,偷懒写法,
class LibVirtualSub : public LibVirtualBase{

public:
    virtual void PrintName() override final
    {
        qDebug() << "LibVirtualSub";
    }
};


LibVirtualBase *CreatLib()
{
    return new LibVirtualSub();
}

#endif
extern "C"
{
    void TestFun()
    {
        qDebug() << "TestFun";
    }
}

二、VS2022 工程应用

1、创建工程

2、将上述工程的 DLL 的头文件,Lib、Dll 文件拷入工程

3、如果本地没有QT 的环境,可用直接从上述工程环境中将 qt/include / QtCore 目录 和 对应的 QtCore.lib、QtCored.lib 拷入当前工程

4、配置属性--> c/c++ ---> 常规--> 包含目录中 -->添加 qtcore 的目录、添加libtest.h 的目录

5、配置属性--> 链接器 ---> 常规--> 附加库目录 -->添加 对应的lib 所在目录

6、配置属性--> 链接器 ---> 输入--> 附加依赖项--> 添加 libtest.lib。

7、程序中调用需要的 类 或者 函数

相关推荐
纵有疾風起20 小时前
C++—string(1):string类的学习与使用
开发语言·c++·经验分享·学习·开源·1024程序员节
郭源潮11 天前
《Muduo网络库:实现TcpServer类终章》
服务器·网络·c++·网络库
MMjeaty1 天前
查找及其算法
c++·算法
yong15858553431 天前
1. Linux C++ muduo 库学习——库的编译安装
linux·c++·学习
mit6.8241 天前
回溯剪枝trick
c++
渡我白衣1 天前
C++世界的混沌边界:undefined_behavior
java·开发语言·c++·人工智能·深度学习·语言模型
却道天凉_好个秋1 天前
c++ 协程
c++
无敌最俊朗@1 天前
视频时间基 (time_base) 详解:时间的“刻度单位”
c++
脏脏a1 天前
【C++ 入门】:引用、内联函数与 C++11 新特性(auto、范围 for、nullptr)全解析
开发语言·c++
AA陈超1 天前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-28 构建属性菜单小部件控制器
c++·游戏·ue5·游戏引擎·虚幻