You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CMakeLists.txt中通过find_package引入Paho MQTT C/C++库

Hey, let's get this sorted out. The undefined reference errors you're seeing happen because you're trying to use old-style CMake variables like ${PAHO_MQTT_C_LIBRARIES} instead of the imported targets that Paho's Config.cmake files actually export. Modern CMake relies on these targets, which handle all the heavy lifting like header paths, system dependencies, and correct linking order automatically.

The Correct CMakeLists.txt Setup

Replace your current config with this:

cmake_minimum_required(VERSION 3.10)
project("Mqtt Test")

# Locate the Paho MQTT C++ library
find_package(PahoMqttCpp REQUIRED)
# Locate the underlying C library (in case the C++ lib doesn't pull it in automatically)
find_package(eclipse-paho-mqtt-c REQUIRED)

add_executable(mqtt_client mqtt_client.cpp)

# Link using the imported targets - no need to manually add pthread/crypto/ssl!
target_link_libraries(mqtt_client
    PRIVATE
        PahoMqttCpp::paho-mqttpp3
        eclipse-paho-mqtt-c::paho-mqtt3as
)

Why Your Previous Approach Failed

Paho's CMake config files don't set those ${PAHO_MQTT_*_LIBRARIES} variables you tried. Instead, they expose namespace-qualified imported targets:

  • For the C++ library: PahoMqttCpp::paho-mqttpp3
  • For the C library: eclipse-paho-mqtt-c::paho-mqtt3as

These targets include everything you need out of the box:

  • Automatic header path inclusion (no need for include_directories)
  • All required system dependencies (pthread, crypto, ssl are already linked via the targets)
  • Correct library linking order to avoid undefined references

If CMake Can't Find the Config Files

If CMake doesn't automatically pick up the Config.cmake files in /usr/local/lib/cmake, you can explicitly set their paths before calling find_package:

# Manually point to the C library's config (if auto-search fails)
set(eclipse-paho-mqtt-c_DIR "/usr/local/lib/cmake/eclipse-paho-mqtt-c")
# Manually point to the C++ library's config
set(PahoMqttCpp_DIR "/usr/local/lib/cmake/PahoMqttCpp")

Quick Checks

  • Make sure your mqtt_client.cpp includes the right headers: #include <mqtt/async_client.h>
  • If you're using a static build of the libraries, the targets might end with -static (e.g., PahoMqttCpp::paho-mqttpp3-static or eclipse-paho-mqtt-c::paho-mqtt3as-static) — adjust accordingly based on how you installed the libraries.

内容的提问来源于stack exchange,提问作者ignacio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:27:35