qt 开发笔记 动态链接库应用

发布于:2024-06-30 ⋅ 阅读:(14) ⋅ 点赞:(0)

1.概要

1.1 需求

库有两种,动态库和静态库,这里说的是动态库;动态库的加载方式有两种,一直是静态的一种是动态的,这里的静态加载是指静态加载动态,是一种加载动态库的方式。也有一种动态加载的方式,只能对外发布函数,无法发布类。

1.2 要点

1.2.1 动态库生成的文件

libtestDll.a: 编译的时候用

testDll.dll:运行的时候用

1.2.2 调用动态库需要引用头文件和依赖库文件(libtestDll.a) 

INCLUDEPATH += $$PWD/include
LIBS += $$PWD/lib/dlltest3

INCLUDEPATH += ./lib
LIBS +=-L./lib - dlltest3

2.代码

2.1 dll工程

testdll.h

#ifndef TESTDLL_H
#define TESTDLL_H

#include "testDll_global.h"

class TESTDLL_EXPORT TestDll
{
public:
    TestDll();
    int add(int a,int b);
};

#endif // TESTDLL_H

 testdll.cpp

#include "testdll.h"

TestDll::TestDll() {}

int TestDll::add(int a,int b){
    return a+b;
}

 testDll_global.h

#ifndef TESTDLL_GLOBAL_H
#define TESTDLL_GLOBAL_H

#include <QtCore/qglobal.h>

#if defined(TESTDLL_LIBRARY)
#define TESTDLL_EXPORT Q_DECL_EXPORT
#else
#define TESTDLL_EXPORT Q_DECL_IMPORT
#endif

#endif // TESTDLL_GLOBAL_H

 .pro

QT -= gui

TEMPLATE = lib
DEFINES += TESTDLL_LIBRARY

CONFIG += c++17


# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    testdll.cpp

HEADERS += \
    testDll_global.h \
    testdll.h

# Default rules for deployment.
unix {
    target.path = /usr/lib
}
!isEmpty(target.path): INSTALLS += target

2.2 调用工程

mian.cpp

#include <QCoreApplication>
#include "./include/testdll.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    TestDll td;
    int b = td.add(2,3);
    qDebug() << "td.add(2,3):"<<b;
    return a.exec();
}

  .pro

QT -= gui

TEMPLATE = lib
DEFINES += TESTDLL_LIBRARY

CONFIG += c++17


# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    testdll.cpp

HEADERS += \
    testDll_global.h \
    testdll.h

# Default rules for deployment.
unix {
    target.path = /usr/lib
}
!isEmpty(target.path): INSTALLS += target

3.运行结果

td.add(2,3): 5

3.参考链接

https://www.cnblogs.com/shiyixirui/p/17596473.html

【Qt专栏】Qt创建和调用动态链接库_qt动态库的创建和调用-CSDN博客 

Qt--动态链接库的创建和使用_qt应用 动态链接库lib-CSDN博客