首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >链接Paho MQTT CMake

链接Paho MQTT CMake
EN

Stack Overflow用户
提问于 2018-06-07 17:38:28
回答 2查看 1.3K关注 0票数 0

我正在尝试编译一个使用PAHO-MQTT的简单测试应用程序。我正在运行Antergos Linux x64。我无法编译我的项目,因为PAHO文件没有链接,并且我不知道如何正确地链接它们。这是我正在尝试编译的Main.cpp。

代码语言:javascript
复制
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "src/MQTTAsync.h"
#include "unistd.h"


#define PUBLISHER 0
volatile MQTTAsync_token deliveredtoken;

int finished = 0;

#if PUBLISHER

#define ADDRESS     "tcp://192.168.2.118:1883"
#define CLIENTID    "Publisher"
#define TOPIC       "test/topic"
#define PAYLOAD     "Hello World!"
#define QOS         1
#define TIMEOUT     10000L

void connlost(void *context, char *cause)
{
        MQTTAsync client = (MQTTAsync)context;
        MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
        int rc;

        printf("\nConnection lost\n");
        printf("     cause: %s\n", cause);

        printf("Reconnecting\n");
        conn_opts.keepAliveInterval = 20;
        conn_opts.cleansession = 1;
        if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
        {
                printf("Failed to start connect, return code %d\n", rc);
                finished = 1;
        }
}


void onDisconnect(void* context, MQTTAsync_successData* response)
{
        printf("Successful disconnection\n");
        finished = 1;
}


void onSend(void* context, MQTTAsync_successData* response)
{
        MQTTAsync client = (MQTTAsync)context;
        MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
        int rc;

        printf("Message with token value %d delivery confirmed\n", response->token);

        opts.onSuccess = onDisconnect;
        opts.context = client;

        if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS)
        {
                printf("Failed to start sendMessage, return code %d\n", rc);
                exit(-1);
        }
}


void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
        printf("Connect failed, rc %d\n", response ? response->code : 0);
        finished = 1;
}


void onConnect(void* context, MQTTAsync_successData* response)
{
        MQTTAsync client = (MQTTAsync)context;
        MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
        MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
        int rc;

        printf("Successful connection\n");

        opts.onSuccess = onSend;
        opts.context = client;

        pubmsg.payload = (void *) PAYLOAD;
        pubmsg.payloadlen = strlen(PAYLOAD);
        pubmsg.qos = QOS;
        pubmsg.retained = 0;
        deliveredtoken = 0;

        if ((rc = MQTTAsync_sendMessage(client, TOPIC, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
        {
                printf("Failed to start sendMessage, return code %d\n", rc);
                exit(-1);
        }
}


int main(int argc, char* argv[])
{
        MQTTAsync client;
        MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
        MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
        MQTTAsync_token token;
        int rc;

        MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);

        MQTTAsync_setCallbacks(client, NULL, connlost, NULL, NULL);

        conn_opts.keepAliveInterval = 20;
        conn_opts.cleansession = 1;
        conn_opts.onSuccess = onConnect;
        conn_opts.onFailure = onConnectFailure;
        conn_opts.context = client;
        if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
        {
                printf("Failed to start connect, return code %d\n", rc);
                exit(-1);
        }

        printf("Waiting for publication of %s\n"
         "on topic %s for client with ClientID: %s\n",
         PAYLOAD, TOPIC, CLIENTID);
        while (!finished)
#if defined(WIN32) || defined(WIN64)
                        Sleep(100);
#else
                        usleep(10000L);
#endif

        MQTTAsync_destroy(&client);
        return rc;
}

#elif PUBLISHER == 0

#define ADDRESS     "tcp://192.168.2.118:1883"
#define CLIENTID    "Subscriber"
#define TOPIC       "test/topic"
#define PAYLOAD     "Hello World!"
#define QOS         1
#define TIMEOUT     10000L

int disc_finished = 0;
int subscribed = 0;

void connlost(void *context, char *cause) {
    MQTTAsync client = (MQTTAsync) context;
    MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
    int rc;

    printf("\nConnection lost\n");
    printf("     cause: %s\n", cause);

    printf("Reconnecting\n");
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) {
        printf("Failed to start connect, return code %d\n", rc);
        finished = 1;
    }
}


int msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message) {
    int i;
    char *payloadptr;

    printf("Message arrived\n");
    printf("     topic: %s\n", topicName);
    printf("   message: ");

    payloadptr = (char *) message->payload;
    for (i = 0; i < message->payloadlen; i++) {
        putchar(*payloadptr++);
    }
    putchar('\n');
    MQTTAsync_freeMessage(&message);
    MQTTAsync_free(topicName);
    return 1;
}


void onDisconnect(void *context, MQTTAsync_successData *response) {
    printf("Successful disconnection\n");
    disc_finished = 1;
}


void onSubscribe(void *context, MQTTAsync_successData *response) {
    printf("Subscribe succeeded\n");
    subscribed = 1;
}

void onSubscribeFailure(void *context, MQTTAsync_failureData *response) {
    printf("Subscribe failed, rc %d\n", response ? response->code : 0);
    finished = 1;
}


void onConnectFailure(void *context, MQTTAsync_failureData *response) {
    printf("Connect failed, rc %d\n", response ? response->code : 0);
    finished = 1;
}


void onConnect(void *context, MQTTAsync_successData *response) {
    MQTTAsync client = (MQTTAsync) context;
    MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
    MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
    int rc;

    printf("Successful connection\n");

    printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
           "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
    opts.onSuccess = onSubscribe;
    opts.onFailure = onSubscribeFailure;
    opts.context = client;

    deliveredtoken = 0;

    if ((rc = MQTTAsync_subscribe(client, TOPIC, QOS, &opts)) != MQTTASYNC_SUCCESS) {
        printf("Failed to start subscribe, return code %d\n", rc);
        exit(-1);
    }
}


int main(int argc, char *argv[]) {
    MQTTAsync client;
    MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
    MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
    MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
    MQTTAsync_token token;
    int rc;
    int ch;

    MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);

    MQTTAsync_setCallbacks(client, NULL, connlost, msgarrvd, NULL);

    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    conn_opts.onSuccess = onConnect;
    conn_opts.onFailure = onConnectFailure;
    conn_opts.context = client;
    if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) {
        printf("Failed to start connect, return code %d\n", rc);
        exit(-1);
    }

    while (!subscribed)
#if defined(WIN32) || defined(WIN64)
        Sleep(100);
#else
        usleep(10000L);
#endif

    if (finished)
        goto exit;

    do {
        ch = getchar();
    } while (ch != 'Q' && ch != 'q');

    disc_opts.onSuccess = onDisconnect;
    if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS) {
        printf("Failed to start disconnect, return code %d\n", rc);
        exit(-1);
    }
    while (!disc_finished)
#if defined(WIN32) || defined(WIN64)
        Sleep(100);
#else
        usleep(10000L);
#endif

    exit:
    MQTTAsync_destroy(&client);
    return rc;
}

#endif

paho mqtt类位于src目录中。在我的CMake中,我尝试这样链接它们:

代码语言:javascript
复制
cmake_minimum_required(VERSION 3.10)
project(MQTT)

set(CMAKE_CXX_STANDARD 11)
file(GLOB src "*.h" "*.c")

add_executable(MQTT main.cpp ${src})

尝试编译时会提示以下异常:

代码语言:javascript
复制
[ 50%] Linking CXX executable MQTT
CMakeFiles/MQTT.dir/main.cpp.o: In function `connlost(user*, char*)':
/home/user/Documents/Projects/MQTT/main.cpp:161: undefined reference to `MQTTAsync_connect'
CMakeFiles/MQTT.dir/main.cpp.o: In function `msgarrvd(user*, char*, int, MQTTAsync_message*)':
/home/user/Documents/Projects/MQTT/main.cpp:181: undefined reference to `MQTTAsync_freeMessage'
/home/user/Documents/Projects/MQTT/main.cpp:182: undefined reference to `MQTTAsync_free'
CMakeFiles/MQTT.dir/main.cpp.o: In function `onConnect(user*, MQTTAsync_successData*)':
/home/user/Documents/Projects/MQTT/main.cpp:226: undefined reference to `MQTTAsync_subscribe'
CMakeFiles/MQTT.dir/main.cpp.o: In function `main':
/home/user/Documents/Projects/MQTT/main.cpp:242: undefined reference to `MQTTAsync_create'
/home/user/Documents/Projects/MQTT/main.cpp:244: undefined reference to `MQTTAsync_setCallbacks'
/home/user/Documents/Projects/MQTT/main.cpp:251: undefined reference to `MQTTAsync_connect'
/home/user/Documents/Projects/MQTT/main.cpp:271: undefined reference to `MQTTAsync_disconnect'
/home/user/Documents/Projects/MQTT/main.cpp:283: undefined reference to `MQTTAsync_destroy'
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/MQTT.dir/build.make:95: MQTT] Error 1
make[2]: *** [CMakeFiles/Makefile2:68: CMakeFiles/MQTT.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:80: CMakeFiles/MQTT.dir/rule] Error 2
make: *** [Makefile:118: MQTT] Error 2

如何正确链接所有这些文件?

EN

回答 2

Stack Overflow用户

发布于 2018-06-07 17:46:39

也许你应该以这种方式包含你的.h/.hpp文件:

代码语言:javascript
复制
set (MQTT_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src/)
target_include_directories (MQTT PUBLIC
                            ${MQTT_INCLUDE_DIR}
                           )

当然,如果您的*.h文件在另一个目录中,您应该更改第一行。

上面的第二行,应该在add_executable之后添加,因为您必须首先创建MQTT目标。

票数 1
EN

Stack Overflow用户

发布于 2021-01-05 23:44:25

这是一个典型的链接错误,因为您没有指定要链接的库,在本例中为libpaho-mqtt3a.so。在CMakeLists.txt中,在add_executable行之后添加以下行

代码语言:javascript
复制
target_link_libraries(MQTT paho-mqtt3a)

我知道这是一个古老的问题,但张贴答案,因为它可能对相同的问题有用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50737937

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档