1.启动Qt creator,依次单击 文件->新建文件或项目->Library->C++库
在detail对话框中选择共享库(Shared library),Core,完成。
此时test_global.h自带两个系统默认导出宏
#ifndef TEST_GLOBAL_H
#define TEST_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(TEST_LIBRARY)
# define TEST_EXPORT Q_DECL_EXPORT
#else
# define TEST_EXPORT Q_DECL_IMPORT
#endif
#endif // TEST_GLOBAL_H
2.在Qt Creator中,在左边“项目”test.h添加
#ifndef TEST_H
#define TEST_H
#include "test_global.h"
class TEST_EXPORT Test
{
public:
Test();
};
#endif // TEST_H
extern "C"
{
TEST_EXPORT int add(int a,int b);
}
我们声明了一个函数add,用于计算a和b并且返回计算的结果。宏TEST_EXPORT的作用是表示函数add()是导出函数。
在test.cpp添加一个函数
#include "test.h"
Test::Test()
{
}
int add(int a ,int b)
{
return a+b;
}
改函数计算a和b的和。保存项目运行构建,在输出目录下将有test.dll
3.利用可视化法调用Qt生成的DLL
(1)启动Qt creator新建一个对话框项目widget,项目名为call。
(2)在设计界面放置一个按钮,将按钮text属性设置为"调用DLL的导出函数",并为按钮添加一个clicked信号的槽函数:
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
QString str;
int sum = add(2,3);
str.sprintf("sum = %d",sum);
QMessageBox::information(this,"rsult",str);
}
其中add()是test.dll中的导出函数
在widget.cpp或者widget.h添加倒数函数声明:
#include "widget.h"
#include "ui_widget.h"
extern "C"
{
int add(int a , int b );
}
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
QString str;
int sum = add(2,3);
str.sprintf("sum = %d",sum);
QMessageBox::information(this,"rsult",str);
}
构建项目,把上面项目的test.dll复制到Qt的可执行生成目录的debug目录下,
并且把Test.lib复制到Qt项目的目录下(和call.pro同一个目录)。
在文件放好后,设置添加库。右击call项目->添加库->外部库-.>库文件找到Test.lib
取消平台下的linux,mac,取消为debug版本添加d作为哦后缀,点击完成代码就被添加进call.pro
运行项目