21、Qt使用LIBS包含的方式调用动态链接库dll中的成员函数

一、功能说明

创建一个总项目,里面包含两个子项目,

子项目1生成动态链接库dll,里面包含一个加法和一个减法;

子项目2是带界面的可执行文件exe,使用LIBS += -L$$PWD/ -lxxx调用子项目1的dll。

二、创建子项目1

打开Qt,点击“NewProject”、“其他项目”、“子目录项目”

更改项目名称和位置

选择编译器

默认

选择子项目1类型,“Library”、“C++库”

选择“共享库”,更改子项目1名称

选择模块

默认

默认

把“libsdll_global.h”中的如下代码,拷贝到“libsdll.h”中

删除“libsdll.h”中的 #include "libsdll_global.h" 这行代码

删除“libsdll_global.h”文件

更改libsdll.h中的代码

#ifndef LIBSDLL_H
#define LIBSDLL_H

#include <QtCore/qglobal.h>

#if defined(LIBSDLL_LIBRARY)
# define LIBSDLLSHARED_EXPORT Q_DECL_EXPORT
#else
# define LIBSDLLSHARED_EXPORT Q_DECL_IMPORT
#endif

class LIBSDLLSHARED_EXPORT LibsDll
{

public:
    LibsDll();

    int addFun(int value1, int value2);

    int subFun(int value1, int value2);
};

#endif // LIBSDLL_H

更改libsdll.cpp中的代码

#include "libsdll.h"

LibsDll::LibsDll()
{
}

int LibsDll::addFun(int value1, int value2)
{
    return (value1 + value2);
}

int LibsDll::subFun(int value1, int value2)
{
    return (value1 - value2);
}

右击子项目1,选择重新构建

构建完成后,子项目1的构建目录下生成“LibsDll.dll”

三、创建子项目2

右击项目名称,选择“新子项目”

选择“Application”、“Qt Widgets Application”

更改子项目2名称

默认

默认

把刚才生成的“LibsDll.dll”和子项目1的"libsdll.h"两个文件拷贝到子项目2中

在子项目2的.pro文件中添加一行代码:LIBS += -L$$PWD/ -lLibsDll

右击子项目2,选择“添加现有文件”

选择"libsdll.h"文件

在子项目2的界面文件mainwindow.ui中添加如下控件,并布局

更改 mainwindow.cpp的代码如下

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "libsdll.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    LibsDll dllLib;
    int ret = dllLib.addFun(ui->lineEdit->text().toInt(), ui->lineEdit_2->text().toInt());
    ui->label->setText(QString::number(ret));
}

void MainWindow::on_pushButton_2_clicked()
{
    LibsDll dllLib;
    int ret = dllLib.subFun(ui->lineEdit->text().toInt(), ui->lineEdit_2->text().toInt());
    ui->label->setText(QString::number(ret));
}

右击子项目2,选择重新构建

构建完成后,再右击子项目2,选择运行。

如果程序运行失败,应用程序输出中显示“程序异常结束”,关闭Qt,重新打开Qt,再运行子项目2

四、运行测试

输入两个数,点击“加法”

点击“减法”

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值