一.编译库文件
1. 创建library项目

2. 选择要配置的编译器

3. 把自动生成的源码都移除:(右键单击,选择 remove)
4
4. 导入库源码
把源码拷贝到项目目录下(.pro 文件所在的目录)

5. 修改 configure.js 文件

cpp
var srcDir = "..";
修改为:
//这里修改成你自己的src目录就行
var srcDir = "E:\\QT_Project\\study\\modbusQN\\libmodbus-3.1.6\\src";
6. 双击 configure.js,然后生成 config.h

- 把生成的 config.h 拷贝到上一级目录 src 目录下。
7. 把项目源码导入到项目中:


8. 修改pro文件
cpp
QT -= gui core
#去除 core 模块
TEMPLATE = lib
DEFINES += MODBUSQN_LIBRARY
#配置为动态库
CONFIG += c++11 dll shared
# 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 += \
libmodbus-3.1.6/src/modbus-data.c \
libmodbus-3.1.6/src/modbus-rtu.c \
libmodbus-3.1.6/src/modbus-tcp.c \
libmodbus-3.1.6/src/modbus.c
HEADERS += \
libmodbus-3.1.6/src/config.h \
libmodbus-3.1.6/src/modbus-private.h \
libmodbus-3.1.6/src/modbus-rtu-private.h \
libmodbus-3.1.6/src/modbus-rtu.h \
libmodbus-3.1.6/src/modbus-tcp-private.h \
libmodbus-3.1.6/src/modbus-tcp.h \
libmodbus-3.1.6/src/modbus-version.h \
libmodbus-3.1.6/src/modbus-version.h.in \
libmodbus-3.1.6/src/modbus.h
#指定头文件搜索目录
INCLUDEPATH += $$PWD/libmodbus-3.1.6/src
#指定依赖文件路径
DEPENDPATH += $$PWD/libmodbus-3.1.6/src
#删除 unix 环境下的配置
# Default rules for deployment.
#unix {
# target.path = /usr/lib
#}
#!isEmpty(target.path): INSTALLS += target
#添加额外的库文件
win32:LIBS += -lws2_32
#指定不是 macOS 系统的 UNIX 平台(macOS 也是一种 unix),还需要使用数学库 libm.so
unix:!macs: LIBS += -lm
# 目标路径(输出目录)
DESTDIR = $$PWD/build
9. 编译
生成如下库文件。

二. 使用库文件
1. 创建测试项目
使用原来配置好的编译器就行

2. 导入库和头文件
拷贝库和头文件都项目目录
在项目目录下创建一个子目录 libmodbus, 在 libmodbus 目录中再创建 lib 和 include 目录
分别用来保存头文件和库文件,如下:

3. 导入库
4. 测试源码
cpp
#include "mainwindow.h"
#include <QApplication>
#include"modbus.h"
#include<QDebug>
int main(int argc, char *argv[])
{
// QApplication a(argc, argv);
// MainWindow w;
// w.show();
// return a.exec();
//创建一个modbus设备
modbus_t *mb = modbus_new_rtu("com5", 9600, 'N', 8, 1);
//连接
modbus_connect(mb);
//选择modbus 从站的地址,从站地址1是开始就设置好了的
modbus_set_slave(mb, 1);
uint16_t regs[4];
// int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest);
//80 是起始地址,4是读取个数,regs是用来存储数据的
modbus_read_registers(mb, 80, 4, regs);
modbus_close(mb);
modbus_free(mb);//释放内从
for (int i = 0; i < 4; i++)
{
qDebug()<<regs[i];
}
return 0;
}
