Qt5建立动态库及调用

Qt5建立动态库及调用

Qt5建立动态库

Step1:点击工具栏 ” 文件 ” →点击项目中列表的” Libaray” →点击右侧” C++库
《Qt5建立动态库及调用》
Step2:类型选择“共享库”,名称自定义(示例名称为“TestDLL1”),路径自定义。

《Qt5建立动态库及调用》
Step3:选择自己需要的编译器。
《Qt5建立动态库及调用》
Step4:选择依赖项,这边可以根据自己的需求来选择动态库中需要使用到的Qt模块。本文做一个简单的动态库,因此不勾选依 赖模块。
《Qt5建立动态库及调用》
Step5:定义类名,头文件名,源文件名。一般与项目名称相同,不作修改。
《Qt5建立动态库及调用》
Step6:点击完成。
《Qt5建立动态库及调用》
Step7:完成后,共生成4个文件,修改一下testdll.h和testdll.cpp函数,增加一个简单的求和成员函数

testdll.h

#ifndef TESTDLL1_H
#define TESTDLL1_H

#include "testdll1_global.h"

class TESTDLL1SHARED_EXPORT TestDLL1
{

public:
    TestDLL1();
    //求和
    int sum(int a,int b);
};

#endif // TESTDLL1_H

testdll.cpp

#include "testdll1.h"


TestDLL1::TestDLL1()
{
}


int TestDLL1::sum(int a ,int b)
{
    return a + b;
}

Step8:点击“运行”,会在目录中生成3个文件,动态库生成完毕。
《Qt5建立动态库及调用》

Qt5调用动态库

Step1:点击工具栏 ” 文件 ” →点击项目中列表的” Application” →点击右侧” Qt Console Application
《Qt5建立动态库及调用》

Step2:名称自定义(示例名称为“ApplictionTest”),路径自定义。
《Qt5建立动态库及调用》

Step3:点击下一步,一直到项目生成完成(编译器选择和生成动态库相同的编译器

Step4:将testdll1_global.h、testdll1.h和TestDLL1.dll复制到ApplictionTest项目目录下
《Qt5建立动态库及调用》
Step5:右键项目,添加现有文件,testdll1_global.h、testdll1.h和TestDLL1.dll加入项目中
《Qt5建立动态库及调用》

Step6:在main.cpp中包含2个头文件,并调用动态库函数

main.cpp

#include <QCoreApplication>
#include <testdll1.h>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    TestDLL1 test;
    printf("%d",test.sum(1,2));
    return a.exec();
}

Step7:修改ApplictionTest.pro配置文件,HEADERS会自动添加,在最后输入LIBS += ./TestDLL1.dll,导入动态库

ApplictionTest.pro

QT -= gui

CONFIG += c++11 console
CONFIG -= app_bundle

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
        main.cpp

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

HEADERS += \
    testdll1.h \
    testdll1_global.h

DISTFILES += \
    TestDLL1.dll

LIBS += ./TestDLL1.dll

Step8:点击生成,会报找不到动态库的错误,可以将testdll1_global.h、testdll1.h和TestDLL1.dll复制到生成的目录下(本文示例为build-ApplictionTest-Desktop_Qt_5_11_1_MinGW_32bit-Debug下)
《Qt5建立动态库及调用》或者点击左侧工具栏“项目”,将Shadow build的勾选去掉
《Qt5建立动态库及调用》
Step9:再次点击运行,结果显示正常,调用成功。
《Qt5建立动态库及调用》

    原文作者:CarbonPie
    原文地址: https://blog.csdn.net/z634863434/article/details/90024332
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞