I'm getting an undefined reference error when compiling the code below.
Here is main.cpp:
#include <iostream>
#include "Person.h"
using namespace std;
int main()
{
Person person1;
cout << "Age is: " << person1.getAge() << endl;
cout << "Name is: " << person1.getName() << endl;
system("PAUSE");
return 0;
}
Here's Person.cpp:
#include "Person.h"
#include <string>
using namespace std;
int Person::getAge()
{
return age;
}
string Person::getName()
{
return name;
}
Here's Person.h:
#ifndef PERSON_H
#define PERSON_H
#include <string>
using namespace std;
class Person
{
private:
int age = 25;
string name = "Jack";
public:
int getAge();
string getName();
};
#endif
Error:
> Executing task: & 'C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin\g++.exe' -g d:\Desktop\howdy\main.cpp -o d:\Desktop\howdy\main.exe <
C:\Users\MAC\AppData\Local\Temp\ccbY6HmM.o: In function `main':
d:/Desktop/howdy/main.cpp:32: undefined reference to `Person::getAge()'
d:/Desktop/howdy/main.cpp:33: undefined reference to `Person::getName[abi:cxx11]()'
collect2.exe: error: ld returned 1 exit status
The terminal process "C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -Command & 'C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin\g++.exe' -g d:\Desktop\howdy\main.cpp -o d:\Desktop\howdy\main.exe" terminated with exit code: 1.
I'm using VS Code with GCC (MinGW). I tried running the build task with g++ and gpp. I checked the c_cpp_properties.json. Also, I read and followed the docs here: https://code.visualstudio.com/docs/cpp/config-mingw
❯ g++ --version
g++.exe (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0
❯ gdb --version
GNU gdb (GDB) 8.1
If I put the class specification and implementation in main.cpp (instead of including it from Person.h), it compiles without issues. This makes me think it's a compiler/linker issue. Any ideas?