Qt文档阅读笔记-共享库的创建与调用

使用共享库的符号

这个符号可以作用在变量、类、函数中,并且这些都可以被调用端使用。

 

在编译共享库中,需要使用export符号。在使用端调用的时候使用import符号。

 

这里是本人从文档中记录的笔记,大部分与以前初学Qt做的笔记差不多,但个人感觉,比以前稍微专业了点,这里指专业词汇方面,毕竟是做的Qt文档阅读笔记。

Qt提供了下面这2个宏,通过这两个宏实现了跨平台导入导出的功能:

Q_DECL_EXPORT

当要编译一个共享库的时候需要使用这个宏。

Q_DECL_IMPORT

当调用端需要调用某个共享库时,需要使用这个宏.

 

在使用Qt Creator创建共享库的时候会指定生成一个文件叫xxx_global.h如下面这个文件:

#ifndef LIBDEMO_GLOBAL_H
#define LIBDEMO_GLOBAL_H

#include <QtCore/qglobal.h>

#if defined(LIBDEMO_LIBRARY)
#  define LIBDEMO_EXPORT Q_DECL_EXPORT
#else
#  define LIBDEMO_EXPORT Q_DECL_IMPORT
#endif

#endif // LIBDEMO_GLOBAL_H

从中可以看到,到如果项目中定义了LIBDEMO_LIBRARY就将LIBDEMO_EXPORT定义为Q_EECL_EXPORT,否则就定义为Q_DECL_IMPORT。

在项目中定义LIBDEMO_LIBRARY的意思是在profile文件中进行定义:

DEFINES += LIBDEMO_LIBRARY

在调用端使用的时候,只要将这个global.h文件以及要用的类的.h文件在调用者.pro文件配置好,随后将dll路径配置好就可以了!!!

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

INCLUDEPATH += D:\QtProject\libDemo

# The following define makes your compiler emit warnings if you use
# any Qt feature that has 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 it uses 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 \
    callLib.cpp

HEADERS += \
    callLib.h

FORMS += \
    callLib.ui

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

#LIBS += D:\QtProject\build-libDemo-Desktop_Qt_5_14_0_MinGW_32_bit-Debug\libDemo.dll

下面是一个小栗子:

 

项目结构如下,笔记结尾会上传到仓库中:

libDemo编译好后,将libDemo.dll放到要调用的exe同目录下:

程序运行

 

源码打包下载地址:
https://github.com/fengfanchen/Qt/tree/master/sharedLibrariesDemo
 

 

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/106757923