如何解决多文件cpp项目中的链接器错误



我有3个文件。一个标头(.h(,一个cpp(.cpp(&主(main.cpp(.

在main中,我只想包含.h文件,而不想包含.cpp来使用这些定义的功能。

这是的文件

人.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

个人.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;
}

所有这些文件都位于同一目录中。我也定义了一个CMakeLists.txt。

CMakeLists.txt

cmake_minimum_required(VERSION "3.7.1")
set(CMAKE_CXX_STANDARD 17)
project("undirected_graph") 
add_executable(${PROJECT_NAME} src/main.cpp )

这是我在编译时收到的错误

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)

当被要求在main.cpp中包含person.h时,链接器的工作不是链接person.herson.cppain.cpp?

顺便说一句,如果我在main.cpp.中包含person.cpp而不是person.h,一切都会正常工作

正如Igor Tandetrik所提到的,您没有在实际构建的中包含person.cpp

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

应该送你去那里。

最新更新