软件版本:QT5.12.0 + Qt Creator4.8.0

  动态链接

  动态链接库又叫"共享库",即sharedLib。

  Qt Creator中新建项目,选择"Library"->"C++ 库"

选择"共享库",选择位置,输入名称:QtSharedLib

选择MinGW构建,一直默认到完成即可!

最终生成如下文件:

完善导出类和导出函数:

编译链接最终生成文件:

  其中.a是导入库,相当于Windows下的lib文件,.dll是共享库文件,相当于Windows下的dll文件,.o是目标文件,相当于Windows下的obj文件。

  共享库的调用:

  1)、使用QLibrary显式链接,需要将dll与exe放在一起

  新建Qt Console应用程序,代码如下:

C++ Code 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

#include <QCoreApplication>
#include <QLibrary>
#include <QDebug>
#include "QtStaticLib.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 声明函数指针
    typedef int (*Add)(int a, int b);
    typedef int (*Sub)(int a, int b);
    typedef int (*Mul)(int a, int b);
    typedef int (*Div)(int a, int b);

    // 显式链接
    QLibrary mylib("QtSharedLib.dll");
    if(!mylib.load())
    {
        // 加载 dll 失败
        qDebug() << "Load QtSharedLib.dll failed!";
        return -1;
    }

    // 需要知道有哪些导出函数,可通过depends.exe查看
    Add add = (Add)mylib.resolve("add");
    Sub sub = (Sub)mylib.resolve("subtraction");
    Mul mul = (Mul)mylib.resolve("multiplication");
    Div div = (Div)mylib.resolve("division");
    if(nullptr == add)
    {
        qDebug() << "Load function add failed!";
        return -1;
    }
    if(nullptr == sub)
    {
        qDebug() << "Load function sub failed!";
        return -1;
    }
    if(nullptr == mul)
    {
        qDebug() << "Load function mul failed!";
        return -1;
    }
    if(nullptr == div)
    {
        qDebug() << "Load function div failed!";
        return -1;
    }

    // 调用函数
    qDebug() << add(1, 2);
    qDebug() << sub(6, 2);
    qDebug() << mul(3, 2);
    qDebug() << div(8, 2);

    return a.exec();
}

  2)、使用隐式链接

  新建Qt Widget应用程序:

  将QtSharedLib工程源码目录下的 QtSharedLib.h、QtSharedLib_global.h和QtSharedLib.a复制到该工程源码目录下,将 QtSharedLib.dll 文件复制到生成exe所在目录中。

  添加.a文件时,可在工程上右键,在弹出的菜单中选择"添加库…"

  

  最后自动在pro文件中加入库链接:

  

  主函数调用:

 C++ Code 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

 # include "Widget.h"
 # include < QApplication >
 # include "QtSharedLib.h"

int main(int argc, char * argv[])
{
    QApplication a(argc, argv);

    // Widget w;
    // w.show();

    QtSharedLib sharedLib;
    sharedLib.showMessage();

    return a.exec();
}

  输出showMessage实现的打印信息:

  

  静态链接

  Qt Creator中新建项目,选择"Library"->"C++ 库"

选择"静态链接库",选择位置,输入名称:QtStaticLib

选择MinGW构建,一直默认到完成即可!

  完善静态库代码

  

  编译生成静态库文件:只有.a和.o文件

  

  静态库的调用

  这里使用隐式链接的方法:

  继续使用前面的Console应用程序,将静态库的.a文件以及.h文件拷贝到工程源码目录下,是"添加库…"操作将库配置写入pro文件

  输出showMessage实现的打印信息:

  

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信