1. 程式人生 > 實用技巧 >Qt_建立C++動態庫DLL

Qt_建立C++動態庫DLL

本文主要學自:https://www.bilibili.com/video/BV1m4411D7NG?from=search&seid=12648539654277089299

為提高程式碼複用性,實現模組化開發,我們通常會對一些常用函式進行封裝,通過呼叫共享庫的方法實現程式碼複用。 Qt自身便能構建共享庫,本教程以QT構建動態連結庫為例進行講解。

本例子,採用Qt Creator 4.11.1版本編寫

1. Qt新建共享庫工程
新建工程, 選擇動態庫, 命名為
DynamicLibrary

這裡注意Type:選擇Shared Library (共享庫),在寫自己的class name:DynamicLibrary,QT module 選擇Core就行

這個選擇編譯器根據自己的程式執行環境選擇32或64位

建立的工程專案,有這幾個檔案

DynamicLibrary.pro檔案,沒有動

 1 QT -= gui
 2 
 3 TEMPLATE = lib
 4 DEFINES += DYNAMICLIBRARY_LIBRARY
 5 
 6 CONFIG += c++11
 7 
 8 # The following define makes your compiler emit warnings if you use
 9 # any Qt feature that has been marked deprecated (the exact warnings
10 # depend on your compiler). Please consult the documentation of the 11 # deprecated API in order to know how to port your code away from it. 12 DEFINES += QT_DEPRECATED_WARNINGS 13 14 # You can also make your code fail to compile if it uses deprecated APIs. 15 # In order to do so, uncomment the following line.
16 # You can also select to disable deprecated APIs only up to a certain version of Qt. 17 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 18 19 SOURCES += \ 20 dynamiclibrary.cpp 21 22 HEADERS += \ 23 DynamicLibrary_global.h \ 24 dynamiclibrary.h 25 26 # Default rules for deployment. 27 unix { 28 target.path = /usr/lib 29 } 30 !isEmpty(target.path): INSTALLS += target

在dynamiclibrary.h檔案,添加了一個測試函式的宣告 int test();

#ifndef DYNAMICLIBRARY_H
#define DYNAMICLIBRARY_H

#include "DynamicLibrary_global.h"

class DYNAMICLIBRARY_EXPORT DynamicLibrary
{
public:
    DynamicLibrary();
    
    int test();//新新增的測試函式
};

#endif // DYNAMICLIBRARY_H

DynamicLibrary_global.h

這個檔案沒有動

#ifndef DYNAMICLIBRARY_GLOBAL_H
#define DYNAMICLIBRARY_GLOBAL_H

#include <QtCore/qglobal.h>

#if defined(DYNAMICLIBRARY_LIBRARY)
#  define DYNAMICLIBRARY_EXPORT Q_DECL_EXPORT
#else
#  define DYNAMICLIBRARY_EXPORT Q_DECL_IMPORT
#endif
#endif // DYNAMICLIBRARY_GLOBAL_H

dynamiclibrary.cpp

#include "dynamiclibrary.h"
#include<QDebug>
DynamicLibrary::DynamicLibrary()
{
}

//測試函式的定義
int DynamicLibrary::test()
{
    int num=10;
    qDebug()<<"動態庫裡面函式的輸出num:"<<num<<endl;
    return num;
}

根據自己的建立專案的地址,在debug資料夾下找到 .dll檔案,就是生成庫檔案

C:\Users\Administrator\Desktop\qttest\build-DynamicLibrary-Desktop_Qt_5_14_2_MinGW_64_bit-Debug\debug
得到共享庫 DynamicLibrary.dll


2. Qt呼叫動態庫

(1)新建一個控制檯工程LoadDynamic , 用於測試呼叫前面構建的動態庫dll

其餘預設就行

下面選相應的64位

生成的專案檔案:

(2)匯入相關標頭檔案,複製標頭檔案至當前測試專案工程路徑下, 接著新增現有檔案

把左邊(以前的編寫封裝的庫檔案的標頭檔案)複製到右邊資料夾(當前測試工程路徑)

複製的效果圖:

再在QT裡面新增現有檔案,把前面拷貝的兩個檔案.h檔案,新增到專案

在main.cpp檔案裡面,新增測試的程式碼和標頭檔案

#include <QCoreApplication>
#include"dynamiclibrary.h"
#include<QDebug>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
  //測試程式碼開始 DynamicLibrary dLib;
int result=dLib.test(); qDebug()<<"result:"<<result<<endl; return a.exec(); }

最後點選執行,效果圖:

最終專案: