0

Hi all I'm getting this error in my code. It says undefined reference Class::function() eventhought i've declared everything in the header file and #include it in the cpp file

main.cpp - My main file

#include "person.h"

int main()
{
    Person person;
    person.setName("John");
    person.setAge(30);
    // print person's name and age
    person.getName();
    person.getAge();

    return 0;
}

person.h - My header file

#include <string>
// create a class named person
class Person
{
private:
    // declare private variables
    std::string name;
    int age;

public:
    // declare setter for name and age variable
    void setName(std::string name);
    void setAge(int age);

    // declare getter for name and age variable
    void getName();
    void getAge();
};

person.cpp - My person cpp file

#include "person.h"

void Person::setName(std::string name)
{
    this->name = name;
}

void Person::setAge(int age)
{
    this->age = age;
}

void Person::getName()
{
    std::cout << "Name: " << this->name << std::endl;
}

void Person::getAge()
{
    std::cout << "Age: " << this->age << std::endl;
}

Error:

cd "c:\Users\yash4\coding-projects\c++" && g++ main.cpp -o main && "c:\Users\yash4\coding-projects\c++"main C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\yash4\AppData\Local\Temp\ccahRsLM.o:main.cpp:(.text+0x54): undefined reference to Person::setName(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)' C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\yash4\AppData\Local\Temp\ccahRsLM.o:main.cpp:(.text+0x7d): undefined reference to Person::setAge(int)' C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\yash4\AppData\Local\Temp\ccahRsLM.o:main.cpp:(.text+0x89): undefined reference to `Person::getName()'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\yash4\AppData\Local\Temp\ccahRsLM.o:main.cpp:(.text+0x95): undefined reference to `Person::getAge()' collect2.exe: error: ld returned 1 exit status

0 Answers0