Home > Mobile >  C External Class Implementation Not Working
C External Class Implementation Not Working

Time:01-25

I am trying to implement my own 'User' class from an external C file. Therefore, I created a User.h, User.cpp and main.cpp file which are all in the same directory. Here you can see the source code of each file:

./User.h

#include <string>

class User {
    public:
        User(std::string username, std::string password);
        std::string getPassword();
        std::string username;

    private:
        std::string password;
};

./User.cpp

#include "User.h"

User::User(std::string username, std::string password) {
    this -> username = username;
    this -> password = password;
}
std::string User::getPassword() {
    return password;
}

./main.cpp

#include <iostream>
#include "User.h"

int main() {
    User eve("Eve3033", "Pass1234");
    std::cout << eve.getPassword();
    return 0;
}

The g compiler error:

undefined reference to `User::User(std::\__cxx11::basic_string\<char, std::char_traits\<char\>, std::allocator\<char\> \>, std::\__cxx11::basic_string\<char, std::char_traits\<char\>, std::allocator\<char\> \>)'
C:\\Users\\wise-\\AppData\\Local\\Temp\\ccQgLvm9.o:main.cpp:(.text 0xb8): undefined reference to `User::getPassword[abi:cxx11]()' collect2.exe: error: ld returned 1 exit status

I tried to remove the std::string User::getPassword() method, which didn't result in any compiling errors. The construction of the User eve("Eve3033", "Pass1234") instance was also successfull and I was able to access the public std::string username attribute.

However, when I tried to implement the std::string User::getPassword() method to also access the private std:string password attribute, g returned the same error.

I searched for the error online and found the following links:

I hope you have any ideas on that problem :)

CodePudding user response:

Your error must be due to a syntax error or missing file in your command. Compiling this code in VS works just fine, and has the expected output. Make sure you have: g main.cpp user.cpp

If you need more context and examples, see here.

  • Related