2025 Master IoT MQTT with C++ | Build Powerful IoT Systems with VSCode


In the Internet of Things (IoT) field, the IoT MQTT protocol has become the mainstream choice for message transmission between devices due to its lightweight, efficient, and reliable characteristics. Whether it’s home automation, smart cities, or various remote monitoring applications, MQTT is a core component of many IoT systems.

IoT MQTT

Why Choose C++ for IoT Development?

In the IoT field, C++ offers the following advantages:

  • High Performance: Faster than Python and Java, making it ideal for resource-constrained embedded devices.
  • Cross-Platform: Can run on Linux, Windows, macOS, and even microcontrollers (MCUs).
  • Powerful Control: Provides direct access to hardware and optimizes resource usage.
  • Perfect Integration with MQTT: Paho MQTT provides high-performance C++ libraries that make it easy to implement real-time communication between IoT devices.

Environment Setup

Before you begin, ensure that you have the following software installed:

  • VSCode (Download)
  • C++ Compiler (GCC/Clang/MSVC)
  • OpenSSL (Required for MQTT SSL/TLS connections)

For macOS/Linux, you need to install OpenSSL:

# Ubuntu / Debian
sudo apt update && sudo apt install libssl-dev

# macOS (using Homebrew)
brew install openssl

Creating a C++ IoT MQTT Project in VSCode

Create a folder called mqtt_client and open VSCode. Then, set up the following file structure:

mqtt_client/
│── build/               # Build output directory  
│── src/                 # C++ source code  
│   └── mqtt_client.cpp  # Main C++ program  
└── CMakeLists.txt       # CMake configuration file

Installing vcpkg (C++ Dependency Manager)

vcpkg is a C++ dependency management tool developed by Microsoft. We will use it to install the Paho MQTT C++ library. Inside the mqtt_client directory, use VSCode’s terminal to download vcpkg:

Install vcpkg

git clone https://github.com/microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh   # macOS / Linux
.\bootstrap-vcpkg.bat  # Windows

Install the MQTT library

./vcpkg install paho-mqttpp3:x64-osx   # macOS
./vcpkg install paho-mqttpp3:x64-windows # Windows
./vcpkg install paho-mqttpp3:x64-linux # Linux

This will install the MQTT library into the mqtt_client/vcpkg/installed/ directory.

Coding the IoT MQTT Client Program

#include <iostream>
#include <mqtt/async_client.h>
#include <chrono>
#include <thread>

const std::string SERVER_ADDRESS = "tcp://broker.hivemq.com:1883";
const std::string CLIENT_ID = "cpp_client";
const std::string TOPIC = "test/topic";

class Callback : public mqtt::callback {
public:
    void message_arrived(mqtt::const_message_ptr msg) override {
        std::cout << "Received message: " << msg->get_topic() << " -> " << msg->to_string() << std::endl;
    }
};

int main() {
    mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);
    Callback cb;
    client.set_callback(cb);

    try {
        std::cout << "Connecting to MQTT broker..." << std::endl;

        // Attempt connection and wait for up to 5 seconds
        auto token = client.connect();
        if (!token->wait_for(std::chrono::seconds(5))) {
            std::cerr << "Failed to connect to MQTT broker!" << std::endl;
            return -1;
        }
        
        std::cout << "Connected successfully!" << std::endl;

        // Subscribe to the topic
        client.subscribe(TOPIC, 1)->wait();
        std::cout << "Subscription successful, waiting for messages..." << std::endl;

        // Simulate publishing messages every 2 seconds
        while (true) {
            client.publish(mqtt::make_message(TOPIC, "Hello MQTT from C++"))->wait();
            std::this_thread::sleep_for(std::chrono::seconds(2));
        }
    } catch (const mqtt::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    client.disconnect()->wait();
    std::cout << "Disconnected." << std::endl;

    return 0;
}

Setting Up the CMake File

In the CMakeLists.txt file, input the following configuration:

cmake_minimum_required(VERSION 3.12)
project(MQTT_Client)

# Set C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Set vcpkg toolchain
set(CMAKE_TOOLCHAIN_FILE "/your_project_directory/mqtt_client/vcpkg/scripts/buildsystems/vcpkg.cmake")

# Manually include vcpkg's Paho MQTT directories
include_directories("/your_project_directory/mqtt_client/vcpkg/installed/x64-osx/include")
link_directories("/your_project_directory/mqtt_client/vcpkg/installed/x64-osx/lib")

# Add executable
add_executable(mqtt_client src/mqtt_client.cpp)

# Manually link Paho MQTT C++ and OpenSSL
target_link_libraries(mqtt_client PRIVATE
    paho-mqttpp3  # Paho MQTT C++ library
    paho-mqtt3a   # Paho MQTT C static library
    paho-mqtt3c
    paho-mqtt3as
    paho-mqtt3cs
    ssl           # OpenSSL
    crypto
)

The entire project will be placed in /your_project_directory/mqtt_client/. Be sure to modify your_project_directory to the actual path.

Building and Running the IoT MQTT Project

In Visual Studio Code (VSCode), you can use the Command Palette to build and run the MQTT client.

In VSCode, press:

  • Cmd + Shift + P (macOS)
  • Ctrl + Shift + P (Windows/Linux)

Then type CMake and you’ll see commands related to CMake.

Configure and build with CMake:

  • In the Command Palette, type CMake: Configure, select the mqtt_client directory, and VSCode will automatically run cmake to generate build settings.
  • If VSCode prompts “No CMake toolchain selected,” type CMake: Select a Kit, and choose either Clang or GCC (depending on your operating system).
  • Press Ctrl (Cmd) + Shift + P, type “CMake: Build”, and press Enter to compile the project.

Run the Program:

./build/mqtt_client

After a successful run, you should see output like this:

Connecting to MQTT broker...
Connected successfully!
Subscribed, waiting for messages...
Message received: test/topic -> Hello MQTT from Python

Conclusion

In 2025, creating a powerful C++ development environment in VS Code has become easier and more efficient. This setup not only streamlines the development process but also gives you the opportunity to explore more advanced C++ features and tools. You can apply this basic IoT MQTT example to more challenging real-world scenarios, such as smart homes, smart agriculture, or remote monitoring. Keep learning and updating your development environment so you can stay ahead in this fast-evolving field.