1

I'm attempting to link my .cpp implementation file with my header file - I get this error message from my mac terminal -

rowlandev:playground rowlandev$ g++ main.cpp -o main
Undefined symbols for architecture x86_64:
  "Person::Person()", referenced from:
      _main in main-32e73b.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Here is the code in my cpp file:

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

using namespace std;

Person::Person() {
    cout << "this is running from the implementation file" << endl;
}

here is the code with my main function:

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

using namespace std;

int main() {
    Person chase;
}

and here is the code in my header file:

  #include <string>

    using namespace std;


    #ifndef playground_h
    #define playground_h

    class Person {
    public:
        Person();
    private:
        string name;
        int age;
    };


    #endif /* playground_h */

what should I do to fix this error? Feel free to add any other things I can do to improve the code I just wrote. Open to anything.

rowlandev
  • 37
  • 7

2 Answers2

1

The link error says that the linked cannot find the constructor. The constructor is not in main.cpp, it is in your other file, which is unnamed in your example. Try putting all of it in a single cpp file to get it working.

vy32
  • 28,461
  • 37
  • 122
  • 246
1

Here's a good read to understand what's going on when you try to create an executable from source code: How does the compilation/linking process work?

What's going on here is that the linker doesn't know where Person::Person(), which is being called in main(), is located. Notice how when you called g++, you never gave it the file where you wrote code for Person::Person().

The right way to call g++ is: $ g++ -o main main.cpp person.cpp

Kartik Prabhu
  • 411
  • 1
  • 4
  • 16