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.