Reputation: 117
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);
}
I am getting error while building using scons as
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.
How to exchange the value of broker between two functions?. Is there any other way to implement this?
Upvotes: 1
Views: 191
Reputation: 341
The problem lies in the fact broker
is not available in the publish_mqtt
function due to variable scoping.
Ie: Once the end brace of mqtt_connection
is hit, broker no longer exists.
int mqtt_connection()
{
mqtt_broker_handle_t *broker = mqtt_connect(client_name, ip_addr, port);
...
}
If you wish to use it within publish_mqtt
you need to shift the scope of the variable to be one that covers both functions. Ie:
mqtt_broker_handle_t *broker = NULL;
int mqtt_connection()
{
broker = mqtt_connect(client_name, ip_addr, port);
...
}
int publish_mqtt()
{
...
}
Upvotes: 0
Reputation: 206667
How to exchange the value of broker between two functions?. Is there any other way to implement this?.
Change the signatures of both functions.
broker
.broker
as an argument.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);
}
Change the calling function.
mqtt_broker_handle_t* broker = mqtt_connection();
publish_mqtt(broker);
Upvotes: 2