0

I'm trying to make a User class, however I'm getting an error output whenever I try to compile this code:

#ifndef LOGIN_H
#define LOGIN_H

#include <string>

/* Classes */
class User {
    std::string username, password;

    public:
    void set_user_username (std::string);
    void set_user_password (std::string);
};

// Sets the User's username
void User::set_user_username (std::string input) {
    username = input;
}

// Sets the User's password
void User::set_user_password (std::string input) {
    password = input;
}

#endif // LOGIN_H

multiple definition of `User::set_user_username(std::string)'

Any clue why it's giving me this error message?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jenny Lee
  • 13
  • 2

2 Answers2

3

You are defining the body of the set_user_username() and set_user_password() methods inside of the header file, but outside of the class declaration. As such, if you include this header file in multiple translation units, regardless of the use of header guards, the linker is going to see multiple object files defining the same methods and fail due to a violation of the One Definition Rule.

You need to either:

  • move the definitions to their own translation unit, and then link that unit in your project:

    Login.h

    #ifndef LOGIN_H
    #define LOGIN_H
    
    #include <string>
    
    /* Classes */
    class User {
        std::string username, password;
    
    public:
        void set_user_username (std::string);
        void set_user_password (std::string);
    };
    
    #endif // LOGIN_H
    

    Login.cpp

    #include "Login.h"
    
    // Sets the User's username
    void User::set_user_username (std::string input) {
        username = input;
    }
    
    // Sets the User's password
    void User::set_user_password (std::string input) {
        password = input;
    }
    
  • move the definitions inline inside the class declaration:

    Login.h

    #ifndef LOGIN_H
    #define LOGIN_H
    
    #include <string>
    
    /* Classes */
    class User {
        std::string username, password;
    
    public:
        void set_user_username (std::string input) {
            username = input;
        }
    
        void set_user_password (std::string input) {
            password = input;
        }
    };
    
    #endif // LOGIN_H
    
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

The definitions are in the header without the inline keyword. Use the inline keyword or move the definitions into a .cpp file.

// Sets the User's username
inline void User::set_user_username (std::string input) {
    username = input;
}

// Sets the User's password
inline void User::set_user_password (std::string input) {
    password = input;
}

multiple definition in header file

shawn1874
  • 1,288
  • 1
  • 10
  • 26