编译时出错 - 链接 .cpp 和头文件
error when compiling - linking .cpp & header file
我正在尝试 link 我的 .cpp 实现文件和我的头文件 - 我从我的 mac 终端收到这条错误消息 -
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)
这是我的 cpp 文件中的代码:
#include <iostream>
#include "playground.h"
using namespace std;
Person::Person() {
cout << "this is running from the implementation file" << endl;
}
这是我主要功能的代码:
#include <iostream>
#include "playground.h"
using namespace std;
int main() {
Person chase;
}
这是我的头文件中的代码:
#include <string>
using namespace std;
#ifndef playground_h
#define playground_h
class Person {
public:
Person();
private:
string name;
int age;
};
#endif /* playground_h */
我应该怎么做才能解决这个错误?随意添加我可以做的任何其他事情来改进我刚刚编写的代码。对任何事情都敞开心扉。
link 错误表示 linked 找不到构造函数。构造函数不在 main.cpp 中,它在您的其他文件中,该文件在您的示例中未命名。尝试将所有这些放在一个 cpp 文件中以使其正常工作。
这里有一本很好的读物,可以帮助您了解当您尝试从源代码创建可执行文件时发生了什么:How does the compilation/linking process work?
这里发生的事情是链接器不知道在 main()
中调用的 Person::Person()
位于何处。请注意,当您调用 g++ 时,您从未将您为 Person::Person()
.
编写代码的文件提供给它
g++的正确调用方式是:
$ g++ -o main main.cpp person.cpp
我正在尝试 link 我的 .cpp 实现文件和我的头文件 - 我从我的 mac 终端收到这条错误消息 -
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)
这是我的 cpp 文件中的代码:
#include <iostream>
#include "playground.h"
using namespace std;
Person::Person() {
cout << "this is running from the implementation file" << endl;
}
这是我主要功能的代码:
#include <iostream>
#include "playground.h"
using namespace std;
int main() {
Person chase;
}
这是我的头文件中的代码:
#include <string>
using namespace std;
#ifndef playground_h
#define playground_h
class Person {
public:
Person();
private:
string name;
int age;
};
#endif /* playground_h */
我应该怎么做才能解决这个错误?随意添加我可以做的任何其他事情来改进我刚刚编写的代码。对任何事情都敞开心扉。
link 错误表示 linked 找不到构造函数。构造函数不在 main.cpp 中,它在您的其他文件中,该文件在您的示例中未命名。尝试将所有这些放在一个 cpp 文件中以使其正常工作。
这里有一本很好的读物,可以帮助您了解当您尝试从源代码创建可执行文件时发生了什么:How does the compilation/linking process work?
这里发生的事情是链接器不知道在 main()
中调用的 Person::Person()
位于何处。请注意,当您调用 g++ 时,您从未将您为 Person::Person()
.
g++的正确调用方式是:
$ g++ -o main main.cpp person.cpp