Search code examples
c++authenticationconnectionmqttpaho

Paho MQTT C++ connection user and password


I am implementing a client to send data over MQTT and I am using Paho MQTT c++ libs. Now I need to add support to user and password authentication and when I try to set them like this:

std::string user = "user";
std::string password = "password";
mqtt::connect_options connOpts;
connOpts.set_user_name(user);
connOpts.set_password(password);

and I get

undefined reference to mqtt::connect_options::set_user_name(std:string const&)

but in the header file connection_options.h

/**
 * Sets the user name to use for the connection.
 * @param userName 
 */
void set_user_name(const std::string& userName);

same thing happens with set_password(password);

Another issue I have is that I haven't been able to keep my connection alive because I can not have the mqtt::async_client object global in the class, I can only create it inside the publish function.

Thanks in advance.


Solution

  • I ran into this issue, and fixed it by adding my own code in the set_user_name and set_password functions in connect_options.h (which aren't initialized in any other file in the C++ wrapper).

    void set_user_name(const std::string& userName){
        const char * usr = userName.c_str();
        opts_.username = usr;
    }
    
    
    void set_password(const std::string& password){
        const char * pw = password.c_str();
        opts_.password = pw;
    }