int mqtt_connection()
{
mqtt_broker_handle_t *broker = mqtt_connect(client_name, ip_addr, port);
if(broker == 0) {
printf("Connection failed, Please check the IP and port of broker\n");
return 0;
}
else {
printf("Connection established successfully\n");
}
return 1;
}
int publish_mqtt()
{
char msg[128] = "Test 2";
if(mqtt_publish(broker, topic1, msg, QoS1) == -1)
{
printf("publish failed\n");
}
else {
printf("Sent messages\n");
}
return(0);
}
我在使用scons构建时遇到错误
master.c: In function 'publish_mqtt':
master.c:39:17: error: 'broker' undeclared (first use in this function)
if(mqtt_publish(broker, topic1, msg, QoS1) == -1)
^
master.c:39:17: note: each undeclared identifier is reported only once for each function it appears in
scons: *** [master.o] Error 1
scons: building terminated because of errors.
如何在两个函数之间交换代理的价值?还有其他方法可以实现吗?
答案 0 :(得分:2)
如何在两个函数之间交换代理的价值?还有其他方法可以实现吗?。
更改两个功能的签名。
broker
。broker
作为参数。mqtt_broker_handle_t* mqtt_connection()
{
mqtt_broker_handle_t *broker = mqtt_connect(client_name, ip_addr, port);
if(broker == 0)
{
printf("Connection failed, Please check the IP and port of broker\n");
return NULL;
}
else
{
printf("Connection established successfully\n");
return broker;
}
}
int publish_mqtt(mqtt_broker_handle_t* broker)
{
char msg[128] = "Test 2";
if(mqtt_publish(broker, topic1, msg, QoS1) == -1)
{
printf("publish failed\n");
}
else
{
printf("Sent messages\n");
}
return(0);
}
更改通话功能。
mqtt_broker_handle_t* broker = mqtt_connection();
publish_mqtt(broker);
答案 1 :(得分:0)
问题在于broker
函数由于变量作用域而无法在publish_mqtt
函数中使用。
即:一旦mqtt_connection
的结束符号被击中,经纪人就不再存在。
int mqtt_connection()
{
mqtt_broker_handle_t *broker = mqtt_connect(client_name, ip_addr, port);
...
}
如果您希望在publish_mqtt
内使用它,则需要将变量的范围转换为涵盖这两个函数的范围。即:
mqtt_broker_handle_t *broker = NULL;
int mqtt_connection()
{
broker = mqtt_connect(client_name, ip_addr, port);
...
}
int publish_mqtt()
{
...
}