下载:mosquitto-2.0.9.tar.gz,cJSON-master.zip,openssl-1.1.0l.tar.gz
解压 tar -xvf mosquitto-2.0.9.tar.gz
cd mosquitto-2.0.9
make && make install
tar -xvf openssl-1.1.0l.tar.gz
Openssl 安装,( --prefix )参数为欲安装之目录
./config --prefix=/usr/local/openssl
执行命令
./config -t
make && make install
cJSON-master.zip
make && make install
按照教程创建工程
在 Visual Studio 中创建 C++ 跨平台项目 | Microsoft Learn
/* Create a new client instance.
* id = NULL -> ask the broker to generate a client id for us
* clean session = true -> the broker should remove old sessions when we connect
* obj = NULL -> we aren't passing any of our private data for callbacks
*/
mosq = mosquitto_new(NULL, true, NULL);
if (mosq == NULL) {
fprintf(stderr, "Error: Out of memory.\n");
return 1;
}
/* Configure callbacks. This should be done before connecting ideally. */
mosquitto_connect_callback_set(mosq, on_connect);
mosquitto_publish_callback_set(mosq, on_publish);
/* Connect to test.mosquitto.org on port 1883, with a keepalive of 60 seconds.
* This call makes the socket connection only, it does not complete the MQTT
* CONNECT/CONNACK flow, you should use mosquitto_loop_start() or
* mosquitto_loop_forever() for processing net traffic. */
rc = mosquitto_connect(mosq, "test.mosquitto.org", 1883, 60);
if (rc != MOSQ_ERR_SUCCESS) {
mosquitto_destroy(mosq);
fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
return 1;
}
/* Run the network loop in a background thread, this call returns quickly. */
rc = mosquitto_loop_start(mosq);
if (rc != MOSQ_ERR_SUCCESS) {
mosquitto_destroy(mosq);
fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
return 1;
}
/* At this point the client is connected to the network socket, but may not
* have completed CONNECT/CONNACK.
* It is fairly safe to start queuing messages at this point, but if you
* want to be really sure you should wait until after a successful call to
* the connect callback.
* In this case we know it is 1 second before we start publishing.
*/
while (1) {
publish_sensor_data(mosq);
}
mosquitto_lib_cleanup();
return 0;
}
将头文件放在本地 mosquitto.h 和main.cpp 在同一个目录
编译时候发现找不到链接库处理方式
出现问题解决
: error while loading shared libraries: libmosquitto.so.1: cannot open shared object file: No such file or directory
解决方法
/etc/ld.so.conf.d/路径下创建任意一个.conf文件,把lib文件的路径写在里面,比如
sudo gedit /etc/ld.so.conf.d/mosqutto.conf
# 写入 存放库的目录
/usr/local/lib
# 保存退出
# 更新缓存
sudo ldconfig
参考连接 (206条消息) error while loading shared libraries: libxxx.so通用解决方法_czafrost的博客-CSDN博客