1.7 KiB
1.7 KiB
Windows MQTT库安装指南
方法1: 使用vcpkg (推荐)
1. 安装vcpkg
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
.\bootstrap-vcpkg.bat
2. 安装MQTT库
.\vcpkg install paho-mqtt:x64-windows
.\vcpkg install paho-mqttpp3:x64-windows
.\vcpkg install nlohmann-json:x64-windows
3. 集成到CMake
.\vcpkg integrate install
4. 修改CMake命令
在构建时添加vcpkg工具链:
mkdir build
cd build
cmake .. -DCMAKE_TOOLCHAIN_FILE=[vcpkg根目录]/scripts/buildsystems/vcpkg.cmake
cmake --build .
方法2: 手动编译
1. 编译Paho MQTT C库
git clone https://github.com/eclipse/paho.mqtt.c.git
cd paho.mqtt.c
mkdir build
cd build
cmake .. -DPAHO_BUILD_STATIC=TRUE -DPAHO_BUILD_SHARED=FALSE
cmake --build . --config Release
cmake --install . --prefix C:/mqtt/c
2. 编译Paho MQTT C++库
git clone https://github.com/eclipse/paho.mqtt.cpp.git
cd paho.mqtt.cpp
mkdir build
cd build
cmake .. -DPAHO_MQTT_C_PATH=C:/mqtt/c -DPAHO_BUILD_STATIC=TRUE
cmake --build . --config Release
cmake --install . --prefix C:/mqtt/cpp
3. 修改CMakeLists.txt
添加库路径:
set(CMAKE_PREFIX_PATH "C:/mqtt/cpp;C:/mqtt/c")
find_package(PahoMqttCpp REQUIRED)
验证安装
运行以下命令验证:
cd build
cmake ..
如果没有错误,说明MQTT库已正确配置。
使用示例
在您的代码中导入MQTT:
#include <mqtt/async_client.h>
#include "mqtt.hpp"
// 创建MQTT客户端
auto mqttClient = std::make_unique<custom::MqttClient>("localhost", 1883, "test_client");
mqttClient->connect();
mqttClient->subscribe("test/topic");