-2

I have 3 files. A header (.h), a cpp (.cpp) & a main (main.cpp).

Inside main I want to include only .h file but not the .cpp to use those functionalities defined.

Here are the files

person.h

#ifndef PERSON_H
#define PERSON_H

#include <string>

class Person {
public:
    Person(std::string &&n) : _name(&n), _address(nullptr) {}
    ~Person() {
        delete _name;
        delete _address;
    }

    void set_name(std::string *name); 
    void set_address(std::string *address);

    std::string get_name();
    std::string get_address();
private:
    std::string *_name;
    std::string *_address;    
};

#endif

person.cpp

#include "person.h"

void Person::set_name(std::string *name) {
    _name = name;
} 
void Person::set_address(std::string *address) {
    _address = address;
}

std::string Person::get_name() {
    return *_name;
}
std::string Person::get_address() {
    return *_address;
}

main.cpp

#include <iostream>

#include "person.h"

int main() {
    Person *John = new Person("John Doe");

    std::cout << john->get_name() << std::endl;

    return 0;
}

All these files reside inside the same directory. I have a CMakeLists.txt defined as well.

CMakeLists.txt

cmake_minimum_required(VERSION "3.7.1")

set(CMAKE_CXX_STANDARD 17)

project("undirected_graph") 

add_executable(${PROJECT_NAME} src/main.cpp )

This is the error I am receiving while compiling

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

Isn't it the linker's job to link the person.h and person.cpp and combine them together to main.cpp when it's asked to include person.h inside main.cpp?

BTW everything works if I include person.cpp instead of person.h inside main.cpp.

Niaz Ahsan
  • 351
  • 1
  • 7
  • 21
  • 2
    You are not compiling or linking `person.cpp`. It's not mentioned anywhere in your make file - how do you expect the compiler or linker to know it even exists? – Igor Tandetnik Jan 09 '21 at 15:51
  • As a question-answer scenario I admire the 1st sentence of yours coz that's helpful. The 2nd one is discouraging just so you know. I respect everyone and expect it back. – Niaz Ahsan Jan 09 '21 at 16:37

1 Answers1

2

As mentioned by Igor Tandetrik, you're not including person.cpp in the actual build

add_executable(${PROJECT_NAME} src/main.cpp src/person.cpp)

Should get you there.

mydisplayname
  • 336
  • 1
  • 5