乐于分享
好东西不私藏

Mosquitto 2.0.22 源码编译文档

Mosquitto 2.0.22 源码编译文档

一、环境要求

1.1 操作系统

  • • 操作系统: Windows 10/11
  • • 架构: x64

1.2 开发工具

  • • 编译器: Visual Studio 2022 Professional
  • • 构建工具: CMake 3.18 或更高版本
  • • Windows SDK: 10.0.26100.0(自动选择)

1.3 依赖库

  • • OpenSSL: 3.0.18(位于 OpenSSL3 目录)
  • • Pthreads4W: v3.0.0(位于 pthreads4w 目录)

二、目录结构

/
├── code/                          # Mosquitto 源码目录
│   ├── cmake/                     # CMake 模块目录
│   │   ├── FindcJSON.cmake
│   │   └── FindPthreads4W.cmake   # 自定义 Pthreads4W 查找模块
│   ├── build/                     # 编译输出目录(编译后生成)
│   │   └── [各子目录]/Release/     # Release 版本编译结果
│   ├── client/                    # 客户端源码
│   ├── lib/                       # 库源码
│   ├── src/                       # 服务器源码
│   ├── apps/                      # 应用程序源码
│   ├── plugins/                   # 插件源码
│   └── CMakeLists.txt            # 主 CMake 配置文件
├── OpenSSL3/                      # OpenSSL 3.0.18 编译结果
│   ├── bin/                       # DLL 文件
│   ├── lib/                       # 库文件(.lib)
│   └── include/                  # 头文件
├── pthreads4w/                    # Pthreads4W 编译结果
│   ├── bin/                       # DLL 文件
│   ├── lib/                       # 库文件(.lib)
│   └── include/                  # 头文件

三、依赖项准备

3.1 OpenSSL 3.0.18

OpenSSL 已编译并放置在 OpenSSL3 目录下,包含:

  • • 头文件OpenSSL3/include/
  • • 库文件OpenSSL3/lib/libcrypto.libOpenSSL3/lib/libssl.lib
  • • DLL 文件OpenSSL3/bin/libcrypto-3.dllOpenSSL3/bin/libssl-3.dll

3.2 Pthreads4W v3.0.0

Pthreads4W 已编译并放置在 pthreads4w 目录下,包含:

  • • 头文件pthreads4w/include/pthread.h 等
  • • 库文件pthreads4w/lib/pthreadVC3.lib 等
  • • DLL 文件pthreads4w/bin/pthreadVC3.dll 等

四、详细编译步骤

4.1 创建 FindPthreads4W.cmake 模块

由于 Mosquitto 的 CMake 配置需要查找 Pthreads4W,但源码中不包含对应的查找模块,需要手动创建。

文件位置code/cmake/FindPthreads4W.cmake

功能:

  • • 查找 Pthreads4W 的头文件和库文件
  • • 支持通过环境变量 PTHREADS4W_DIR 指定路径
  • • 创建导入目标 PThreads4W::PThreads4W 供链接使用

关键代码:

FIND_PATH(
    PTHREADS4W_INCLUDE_DIR
    pthread.h
    HINTS
        ${PTHREADS4W_DIR}
        ${PTHREADS4W_DIR}/include
)

FIND_LIBRARY( PTHREADS4W_LIBRARY
    NAMES pthreadVC3 pthread
    HINTS 
        ${PTHREADS4W_DIR}
        ${PTHREADS4W_DIR}/lib
)

4.2 配置 CMake 构建

在 PowerShell 中执行以下命令:

# 进入源码目录(假设当前在项目根目录)
cd code

# 创建构建目录
if (-not (Test-Path build)) { 
    New-Item -ItemType Directory -Path build 
}

# 进入构建目录
cd build

# 获取项目根目录的绝对路径(用于设置环境变量)
$projectRoot = Resolve-Path "..\.."

# 设置环境变量(使用相对路径转换为绝对路径)
$env:OPENSSL_ROOT_DIR = Join-Path $projectRoot "OpenSSL3"
$env:PTHREADS4W_DIR = Join-Path $projectRoot "pthreads4w"

# 配置 CMake
cmake .. `
    -G "Visual Studio 17 2022" `
    -A x64 `
    -DPTHREADS4W_DIR="$env:PTHREADS4W_DIR" `
    -DOPENSSL_ROOT_DIR="$env:OPENSSL_ROOT_DIR"

或者使用相对路径直接指定(如果从 build 目录执行):

# 从 build 目录配置,直接使用相对路径
cmake .. `
    -G "Visual Studio 17 2022" `
    -A x64 `
    -DPTHREADS4W_DIR="..\..\pthreads4w" `
    -DOPENSSL_ROOT_DIR="..\..\OpenSSL3"

配置说明:

  • • -G "Visual Studio 17 2022": 指定生成 Visual Studio 2022 解决方案
  • • -A x64: 指定目标架构为 x64
  • • -DPTHREADS4W_DIR: 指定 Pthreads4W 根目录
  • • -DOPENSSL_ROOT_DIR: 指定 OpenSSL 根目录

配置输出:

-- Found OpenSSL: .../OpenSSL3/lib/libcrypto.lib (found version "3.0.18")
-- Found Pthreads4W: .../pthreads4w/include
-- WITH_DLT = OFF
-- Could NOT find cJSON (missing: CJSON_INCLUDE_DIR CJSON_LIBRARY)
-- Optional dependency cJSON not found. Some features will be disabled.
-- Configuring done
-- Generating done

注意: cJSON 是可选的依赖项,未找到不影响基本功能编译。

4.3 修复编译错误

问题 1: Unicode 字符编码错误

错误信息:

...\client\client_shared.c(1199,27): error C2001: 常量中有换行符
...\client\client_shared.c(1200,6): error C2146: 语法错误: 缺少")"(在标识符"cfg"的前面)

原因:
client_shared.c 第 1199 行使用了 Unicode 字符 (无穷符号),Windows MSVC 编译器在默认代码页(936,GBK)下无法正确解析该字符。

解决方案:
修改 code/client/client_shared.c 文件第 1199 行:

修改前:

if(!strcmp(argv[i+1], "∞")){

修改后:

if(!strcmp(argv[i+1], "inf") || !strcmp(argv[i+1], "infinity")){

这样既解决了编译错误,又保持了功能完整性(支持 “inf” 和 “infinity” 作为无穷大的表示)。

4.4 执行编译

# 在 build 目录下执行
cmake --build . --config Release

编译选项说明:

  • • --config Release: 编译 Release 版本(优化版本,适合生产环境)
  • • 也可以使用 --config Debug 编译调试版本

编译过程:

  1. 1. 编译服务器 (mosquitto.exe)
  2. 2. 编译客户端库 (mosquitto.dll)
  3. 3. 编译 C++ 客户端库 (mosquittopp.dll)
  4. 4. 编译客户端工具 (mosquitto_pub.exemosquitto_sub.exemosquitto_rr.exe)
  5. 5. 编译应用程序 (mosquitto_passwd.exe)
  6. 6. 编译插件 (mosquitto_payload_modification.dll)

编译时间: 约 2-5 分钟(取决于机器性能)

五、编译结果

5.1 生成的文件列表

所有编译生成的文件位于 code/build/*/Release/ 目录下:

文件名
类型
路径
说明
mosquitto.exe
可执行文件
src/Release/
MQTT 代理服务器
mosquitto.dll
动态库
lib/Release/
C 客户端库
mosquittopp.dll
动态库
lib/cpp/Release/
C++ 客户端库
mosquitto_pub.exe
可执行文件
client/Release/
MQTT 发布客户端
mosquitto_sub.exe
可执行文件
client/Release/
MQTT 订阅客户端
mosquitto_rr.exe
可执行文件
client/Release/
MQTT 请求-响应客户端
mosquitto_passwd.exe
可执行文件
apps/mosquitto_passwd/Release/
密码文件管理工具
mosquitto_payload_modification.dll
插件
plugins/payload-modification/Release/
负载修改插件

5.2 依赖的 DLL 文件

运行时需要以下 DLL 文件(需在系统 PATH 中或与可执行文件同目录):

  • • pthreadVC3.dll – 从 pthreads4w/bin/ 复制
  • • libcrypto-3.dll – 从 OpenSSL3/bin/ 复制
  • • libssl-3.dll – 从 OpenSSL3/bin/ 复制

五、安装编译成果

编译完成后,可以将所有编译成果复制到单独的安装目录,便于部署和使用。

5.3 创建安装目录结构

# 在项目根目录下创建安装目录
$installDir = "mosquitto-install"
New-Item -ItemType Directory -Path $installDir -Force | Out-Null
New-Item -ItemType Directory -Path "$installDir\bin" -Force | Out-Null
New-Item -ItemType Directory -Path "$installDir\lib" -Force | Out-Null
New-Item -ItemType Directory -Path "$installDir\include" -Force | Out-Null
New-Item -ItemType Directory -Path "$installDir\etc" -Force | Out-Null
New-Item -ItemType Directory -Path "$installDir\plugins" -Force | Out-Null

5.4 复制编译成果

使用以下 PowerShell 脚本将所有编译成果复制到安装目录:

# 设置路径变量
$projectRoot = Get-Location
$buildDir = Join-Path $projectRoot "code\build"
$installDir = Join-Path $projectRoot "mosquitto-install"

# 1. 复制可执行文件到 bin 目录
Write-Host "复制可执行文件..." -ForegroundColor Green
Copy-Item "$buildDir\src\Release\mosquitto.exe" -Destination "$installDir\bin\" -Force
Copy-Item "$buildDir\client\Release\mosquitto_pub.exe" -Destination "$installDir\bin\" -Force
Copy-Item "$buildDir\client\Release\mosquitto_sub.exe" -Destination "$installDir\bin\" -Force
Copy-Item "$buildDir\client\Release\mosquitto_rr.exe" -Destination "$installDir\bin\" -Force
Copy-Item "$buildDir\apps\mosquitto_passwd\Release\mosquitto_passwd.exe" -Destination "$installDir\bin\" -Force

# 2. 复制 DLL 文件到 bin 目录
Write-Host "复制 DLL 文件..." -ForegroundColor Green
Copy-Item "$buildDir\lib\Release\mosquitto.dll" -Destination "$installDir\bin\" -Force
Copy-Item "$buildDir\lib\cpp\Release\mosquittopp.dll" -Destination "$installDir\bin\" -Force

# 3. 复制库文件(.lib)到 lib 目录
Write-Host "复制库文件..." -ForegroundColor Green
Copy-Item "$buildDir\lib\Release\mosquitto.lib" -Destination "$installDir\lib\" -Force
Copy-Item "$buildDir\lib\cpp\Release\mosquittopp.lib" -Destination "$installDir\lib\" -Force

# 4. 复制头文件到 include 目录
Write-Host "复制头文件..." -ForegroundColor Green
Copy-Item "$projectRoot\code\include\*.h" -Destination "$installDir\include\" -Force

# 5. 复制插件到 plugins 目录
Write-Host "复制插件..." -ForegroundColor Green
Copy-Item "$buildDir\plugins\payload-modification\Release\mosquitto_payload_modification.dll" `
    -Destination "$installDir\plugins\" -Force

# 6. 复制配置文件到 etc 目录
Write-Host "复制配置文件..." -ForegroundColor Green
Copy-Item "$projectRoot\code\mosquitto.conf" -Destination "$installDir\etc\" -Force
Copy-Item "$projectRoot\code\aclfile.example" -Destination "$installDir\etc\" -Force
Copy-Item "$projectRoot\code\pskfile.example" -Destination "$installDir\etc\" -Force
Copy-Item "$projectRoot\code\pwfile.example" -Destination "$installDir\etc\" -Force

# 7. 复制依赖的 DLL 文件到 bin 目录
Write-Host "复制依赖 DLL 文件..." -ForegroundColor Green
Copy-Item "$projectRoot\pthreads4w\bin\pthreadVC3.dll" -Destination "$installDir\bin\" -Force
Copy-Item "$projectRoot\OpenSSL3\bin\libcrypto-3.dll" -Destination "$installDir\bin\" -Force
Copy-Item "$projectRoot\OpenSSL3\bin\libssl-3.dll" -Destination "$installDir\bin\" -Force

Write-Host "`n安装完成!文件已复制到: $installDir" -ForegroundColor Green

5.5 一键安装脚本

将以下内容保存为 install.ps1 文件,在项目根目录执行即可完成安装:

# Mosquitto 2.0.22 安装脚本
# 使用方法: .\install.ps1 [安装目录名]

param(
    [string]$InstallDir = "mosquitto-install"
)

$ErrorActionPreference = "Stop"

# 获取脚本所在目录(项目根目录)
$projectRoot = $PSScriptRoot
if (-not $projectRoot) {
    $projectRoot = Get-Location
}

$buildDir = Join-Path $projectRoot "code\build"
$targetDir = Join-Path $projectRoot $InstallDir

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Mosquitto 2.0.22 安装脚本" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "项目根目录: $projectRoot" -ForegroundColor Yellow
Write-Host "构建目录: $buildDir" -ForegroundColor Yellow
Write-Host "安装目录: $targetDir" -ForegroundColor Yellow
Write-Host ""

# 检查构建目录是否存在
if (-not (Test-Path $buildDir)) {
    Write-Host "错误: 构建目录不存在,请先编译项目!" -ForegroundColor Red
    exit 1
}

# 创建安装目录结构
Write-Host "创建安装目录结构..." -ForegroundColor Green
$dirs = @("bin", "lib", "include", "etc", "plugins")
foreach ($dir in $dirs) {
    $path = Join-Path $targetDir $dir
    if (-not (Test-Path $path)) {
        New-Item -ItemType Directory -Path $path -Force | Out-Null
    }
}

# 复制文件函数
function Copy-File {
    param(
        [string]$Source,
        [string]$Destination,
        [string]$Description
    )
    if (Test-Path $Source) {
        Copy-Item $Source -Destination $Destination -Force
        Write-Host "  ✓ $Description" -ForegroundColor Gray
        return $true
    } else {
        Write-Host "  ✗ $Description (文件不存在)" -ForegroundColor Yellow
        return $false
    }
}

# 1. 复制可执行文件
Write-Host "`n[1/7] 复制可执行文件..." -ForegroundColor Cyan
Copy-File "$buildDir\src\Release\mosquitto.exe" "$targetDir\bin\mosquitto.exe" "mosquitto.exe"
Copy-File "$buildDir\client\Release\mosquitto_pub.exe" "$targetDir\bin\mosquitto_pub.exe" "mosquitto_pub.exe"
Copy-File "$buildDir\client\Release\mosquitto_sub.exe" "$targetDir\bin\mosquitto_sub.exe" "mosquitto_sub.exe"
Copy-File "$buildDir\client\Release\mosquitto_rr.exe" "$targetDir\bin\mosquitto_rr.exe" "mosquitto_rr.exe"
Copy-File "$buildDir\apps\mosquitto_passwd\Release\mosquitto_passwd.exe" "$targetDir\bin\mosquitto_passwd.exe" "mosquitto_passwd.exe"

# 2. 复制 DLL 文件
Write-Host "`n[2/7] 复制 DLL 文件..." -ForegroundColor Cyan
Copy-File "$buildDir\lib\Release\mosquitto.dll" "$targetDir\bin\mosquitto.dll" "mosquitto.dll"
Copy-File "$buildDir\lib\cpp\Release\mosquittopp.dll" "$targetDir\bin\mosquittopp.dll" "mosquittopp.dll"

# 3. 复制库文件
Write-Host "`n[3/7] 复制库文件..." -ForegroundColor Cyan
Copy-File "$buildDir\lib\Release\mosquitto.lib" "$targetDir\lib\mosquitto.lib" "mosquitto.lib"
Copy-File "$buildDir\lib\cpp\Release\mosquittopp.lib" "$targetDir\lib\mosquittopp.lib" "mosquittopp.lib"

# 4. 复制头文件
Write-Host "`n[4/7] 复制头文件..." -ForegroundColor Cyan
$headerFiles = Get-ChildItem "$projectRoot\code\include\*.h" -ErrorAction SilentlyContinue
if ($headerFiles) {
    foreach ($file in $headerFiles) {
        Copy-File $file.FullName "$targetDir\include\$($file.Name)" $file.Name
    }
} else {
    Write-Host "  ✗ 未找到头文件" -ForegroundColor Yellow
}

# 5. 复制插件
Write-Host "`n[5/7] 复制插件..." -ForegroundColor Cyan
Copy-File "$buildDir\plugins\payload-modification\Release\mosquitto_payload_modification.dll" `
    "$targetDir\plugins\mosquitto_payload_modification.dll" "mosquitto_payload_modification.dll"

# 6. 复制配置文件
Write-Host "`n[6/7] 复制配置文件..." -ForegroundColor Cyan
Copy-File "$projectRoot\code\mosquitto.conf" "$targetDir\etc\mosquitto.conf" "mosquitto.conf"
Copy-File "$projectRoot\code\aclfile.example" "$targetDir\etc\aclfile.example" "aclfile.example"
Copy-File "$projectRoot\code\pskfile.example" "$targetDir\etc\pskfile.example" "pskfile.example"
Copy-File "$projectRoot\code\pwfile.example" "$targetDir\etc\pwfile.example" "pwfile.example"

# 7. 复制依赖 DLL
Write-Host "`n[7/7] 复制依赖 DLL 文件..." -ForegroundColor Cyan
Copy-File "$projectRoot\pthreads4w\bin\pthreadVC3.dll" "$targetDir\bin\pthreadVC3.dll" "pthreadVC3.dll"
Copy-File "$projectRoot\OpenSSL3\bin\libcrypto-3.dll" "$targetDir\bin\libcrypto-3.dll" "libcrypto-3.dll"
Copy-File "$projectRoot\OpenSSL3\bin\libssl-3.dll" "$targetDir\bin\libssl-3.dll" "libssl-3.dll"

# 显示安装结果
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "安装完成!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "安装目录: $targetDir" -ForegroundColor Yellow
Write-Host "`n目录结构:" -ForegroundColor Yellow
Write-Host "  $targetDir" -ForegroundColor White
Write-Host "  ├── bin\          # 可执行文件和 DLL" -ForegroundColor White
Write-Host "  ├── lib\          # 库文件 (.lib)" -ForegroundColor White
Write-Host "  ├── include\      # 头文件" -ForegroundColor White
Write-Host "  ├── etc\          # 配置文件" -ForegroundColor White
Write-Host "  └── plugins\      # 插件" -ForegroundColor White
Write-Host "`n使用方法:" -ForegroundColor Yellow
Write-Host "  # 运行服务器" -ForegroundColor White
Write-Host "  cd $targetDir\bin" -ForegroundColor Gray
Write-Host "  .\mosquitto.exe -c ..\etc\mosquitto.conf" -ForegroundColor Gray

使用方法:

# 使用默认安装目录名 "mosquitto-install"
.\install.ps1

# 或指定自定义安装目录名
.\install.ps1 -InstallDir "mosquitto-2.0.22"

5.6 安装目录结构

安装完成后,目录结构如下:

mosquitto-install/
├── bin/                              # 可执行文件和 DLL
│   ├── mosquitto.exe                 # MQTT 代理服务器
│   ├── mosquitto_pub.exe             # 发布客户端
│   ├── mosquitto_sub.exe             # 订阅客户端
│   ├── mosquitto_rr.exe              # 请求-响应客户端
│   ├── mosquitto_passwd.exe          # 密码管理工具
│   ├── mosquitto.dll                 # C 客户端库
│   ├── mosquittopp.dll               # C++ 客户端库
│   ├── pthreadVC3.dll                # Pthreads4W DLL
│   ├── libcrypto-3.dll               # OpenSSL 加密库
│   └── libssl-3.dll                  # OpenSSL SSL 库
├── lib/                              # 库文件(用于开发)
│   ├── mosquitto.lib                 # C 客户端库(导入库)
│   └── mosquittopp.lib               # C++ 客户端库(导入库)
├── include/                          # 头文件(用于开发)
│   ├── mosquitto.h
│   ├── mosquittopp.h
│   ├── mosquitto_broker.h
│   └── mqtt_protocol.h
├── etc/                              # 配置文件
│   ├── mosquitto.conf                # 主配置文件
│   ├── aclfile.example               # ACL 文件示例
│   ├── pskfile.example               # PSK 文件示例
│   └── pwfile.example                # 密码文件示例
└── plugins/                          # 插件目录
    └── mosquitto_payload_modification.dll

5.7 验证安装

安装完成后,可以验证安装是否成功:

# 进入安装目录的 bin 目录
cd mosquitto-install\bin

# 检查文件是否存在
Get-ChildItem | Select-Object Name, Length

# 测试运行(查看版本信息)
.\mosquitto.exe --help

# 测试客户端工具
.\mosquitto_pub.exe --help
.\mosquitto_sub.exe --help

六、使用说明

6.1 运行 MQTT 代理服务器

如果已安装到单独目录(推荐):

# 进入安装目录
cd mosquitto-install\bin

# 基本运行(使用默认配置)
.\mosquitto.exe

# 指定配置文件
.\mosquitto.exe -c ..\etc\mosquitto.conf

# 前台运行并显示日志
.\mosquitto.exe -v -c ..\etc\mosquitto.conf

如果使用编译目录

# 基本运行(使用默认配置)
.\code\build\src\Release\mosquitto.exe

# 指定配置文件
.\code\build\src\Release\mosquitto.exe -c .\code\mosquitto.conf

# 前台运行并显示日志
.\code\build\src\Release\mosquitto.exe -v

6.2 使用客户端工具

如果已安装到单独目录(推荐):

# 进入安装目录的 bin 目录
cd mosquitto-install\bin

# 发布消息
.\mosquitto_pub.exe -h localhost -p 1883 -t "test/topic" -m "Hello, Mosquitto!"

# 订阅主题
.\mosquitto_sub.exe -h localhost -p 1883 -t "test/topic" -v

# 请求-响应模式
# 响应端
.\mosquitto_rr.exe -h localhost -t "request/topic" -R "response/topic"
# 请求端
.\mosquitto_rr.exe -h localhost -t "request/topic" -R "response/topic" -m "Request message"

如果使用编译目录

# 发布消息
.\code\build\client\Release\mosquitto_pub.exe `
    -h localhost `
    -p 1883 `
    -t "test/topic" `
    -m "Hello, Mosquitto!"

# 订阅主题
.\code\build\client\Release\mosquitto_sub.exe `
    -h localhost `
    -p 1883 `
    -t "test/topic" `
    -v

# 请求-响应模式
# 响应端
.\code\build\client\Release\mosquitto_rr.exe `
    -h localhost `
    -t "request/topic" `
    -R "response/topic"
# 请求端
.\code\build\client\Release\mosquitto_rr.exe `
    -h localhost `
    -t "request/topic" `
    -R "response/topic" `
    -m "Request message"

6.3 管理密码文件

如果已安装到单独目录(推荐):

cd mosquitto-install\bin

# 创建密码文件
.\mosquitto_passwd.exe -c ..\etc\pwfile.txt username

# 添加用户到密码文件
.\mosquitto_passwd.exe ..\etc\pwfile.txt username2

如果使用编译目录

# 创建密码文件
.\code\build\apps\mosquitto_passwd\Release\mosquitto_passwd.exe `
    -c .\pwfile.txt username

# 添加用户到密码文件
.\code\build\apps\mosquitto_passwd\Release\mosquitto_passwd.exe `
    .\pwfile.txt username2

6.4 在代码中使用客户端库

C 语言示例

#include <mosquitto.h>

int
 main() {
struct mosquitto *mosq;


    mosquitto_lib_init();
    mosq = mosquitto_new("client-id", true, NULL);

    if
 (mosquitto_connect(mosq, "localhost", 1883, 60) != MOSQ_ERR_SUCCESS) {
        fprintf
(stderr, "Unable to connect.\n");
        return
 1;
    }

    mosquitto_publish(mosq, NULL, "test/topic", 5, "hello", 0, false);

    mosquitto_disconnect(mosq);
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();

    return
 0;
}

编译命令(使用安装目录):

# 使用安装目录中的头文件和库文件
cl.exe /I"mosquitto-install\include" /I"pthreads4w\include" /I"OpenSSL3\include" `
    example.c /link /LIBPATH:"mosquitto-install\lib" `
    /LIBPATH:"pthreads4w\lib" /LIBPATH:"OpenSSL3\lib" `
    mosquitto.lib pthreadVC3.lib libcrypto.lib libssl.lib ws2_32.lib

编译命令(使用编译目录):

cl.exe /I"code\include" /I"pthreads4w\include" /I"OpenSSL3\include" `
    example.c /link /LIBPATH:"code\build\lib\Release" `
    /LIBPATH:"pthreads4w\lib" /LIBPATH:"OpenSSL3\lib" `
    mosquitto.lib pthreadVC3.lib libcrypto.lib libssl.lib ws2_32.lib

C++ 语言示例

#include <mosquittopp.h>

class
 MyMosq : public mosqpp::mosquittopp {
public
:
    MyMosq
(const char *id) : mosqpp::mosquittopp(id) {}

void on_connect(int rc)
{
        if
 (rc == 0) {
            subscribe
(NULL, "test/topic");
        }
    }

void on_message(const struct mosquitto_message *message)
{
        printf
("Topic: %s, Message: %s\n"
               message->topic, (char*)message->payload);
    }
};

int main()
{
    mosqpp::lib_init();
    MyMosq client("client-id")
;

    client.connect("localhost", 1883, 60);
    client.loop_forever();

    mosqpp::lib_cleanup();
    return
 0;
}

七、常见问题

7.1 找不到 DLL 文件

问题: 运行时提示找不到 pthreadVC3.dll 或 OpenSSL DLL。

解决方案:

  1. 1. 将 DLL 文件复制到可执行文件同目录
  2. 2. 或将 DLL 所在目录添加到系统 PATH 环境变量

如果使用编译目录

# 复制 DLL 到 Release 目录
Copy-Item "pthreads4w\bin\pthreadVC3.dll" `
    -Destination "code\build\src\Release\"
Copy-Item "OpenSSL3\bin\*.dll" `
    -Destination "code\build\src\Release\"

如果已安装到单独目录(推荐):
安装脚本已经自动将所有依赖 DLL 复制到 mosquitto-install\bin\ 目录,无需手动复制。

7.2 端口被占用

问题: 启动服务器时提示端口 1883 已被占用。

解决方案:

  1. 1. 修改配置文件中的端口号
  2. 2. 或使用 -p 参数指定其他端口
.\code\build\src\Release\mosquitto.exe -p 1884

7.3 编译时找不到 OpenSSL

问题: CMake 配置时提示找不到 OpenSSL。

解决方案:
确保设置了正确的 OPENSSL_ROOT_DIR 环境变量,或使用 CMake 参数:

# 使用相对路径(从 build 目录执行)
cmake .. -DOPENSSL_ROOT_DIR="..\..\OpenSSL3"

# 或使用绝对路径
$opensslPath = Resolve-Path "..\..\OpenSSL3"
cmake .. -DOPENSSL_ROOT_DIR="$opensslPath"

7.4 编译时找不到 Pthreads4W

问题: CMake 配置时提示找不到 Pthreads4W。

解决方案:

  1. 1. 确保 FindPthreads4W.cmake 文件存在于 code/cmake/ 目录
  2. 2. 设置 PTHREADS4W_DIR 环境变量或 CMake 参数
# 使用相对路径(从 build 目录执行)
cmake .. -DPTHREADS4W_DIR="..\..\pthreads4w"

# 或使用绝对路径
$pthreadsPath = Resolve-Path "..\..\pthreads4w"
cmake .. -DPTHREADS4W_DIR="$pthreadsPath"

八、编译配置选项

8.1 主要 CMake 选项

选项
默认值
说明
WITH_TLS
ON
启用 TLS/SSL 支持
WITH_THREADING
ON
启用线程支持
WITH_BROKER
ON
编译代理服务器
WITH_CLIENTS
ON
编译客户端工具
WITH_APPS
ON
编译应用程序
WITH_PLUGINS
ON
编译插件
WITH_CJSON
ON
启用 cJSON 支持(可选)

8.2 禁用某些功能

如果不需要某些功能,可以在 CMake 配置时禁用:

# 禁用 TLS 支持
cmake .. -DWITH_TLS=OFF

# 禁用插件
cmake .. -DWITH_PLUGINS=OFF

九、重新编译

如果需要重新编译:

# 进入构建目录(假设当前在项目根目录)
cd code\build

# 清理构建目录
Remove-Item -Recurse -Force *

# 重新配置(使用相对路径)
cmake .. -G "Visual Studio 17 2022" -A x64 `
    -DPTHREADS4W_DIR="..\..\pthreads4w" `
    -DOPENSSL_ROOT_DIR="..\..\OpenSSL3"

# 重新编译
cmake --build . --config Release

十、总结

本次编译成功完成了 Mosquitto 2.0.22 在 Windows 平台上的编译,主要工作包括:

  1. 1. ✅ 创建了 FindPthreads4W.cmake 模块以支持 Pthreads4W 库的查找
  2. 2. ✅ 配置了 CMake 构建系统,正确指定了 OpenSSL 和 Pthreads4W 的路径
  3. 3. ✅ 修复了 Unicode 字符编码导致的编译错误
  4. 4. ✅ 成功编译了所有组件(服务器、客户端库、工具程序、插件)

所有编译生成的文件位于 code/build/*/Release/ 目录下,可以直接使用。


作者信息

网站:www.itgather.com
邮箱:itgather@163.com
公众号: 全栈代码工坊

本文首发于 IT Gather 技术社区,欢迎关注我们的公众号获取更多技术分享。


下载链接

网页分享1:mosquitto2.0.22源码编译.rar

本站文章均为手工撰写未经允许谢绝转载:夜雨聆风 » Mosquitto 2.0.22 源码编译文档

评论 抢沙发

3 + 4 =
  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
×
订阅图标按钮