编译-链接.cpp&时出错头文件 [英] error when compiling - linking .cpp & header file
问题描述
我正在尝试将.cpp实现文件与头文件链接-我从mac终端收到此错误消息-
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)
这是我的cpp文件中的代码:
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.
推荐答案
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?
这里发生的是链接器不知道在main()
中被调用的Person::Person()
的位置.请注意,当您调用g ++时,从未将文件提供给您为Person::Person()
编写代码的地方.
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()
.
调用g ++的正确方法是:
$ g++ -o main main.cpp person.cpp
The right way to call g++ is:
$ g++ -o main main.cpp person.cpp
这篇关于编译-链接.cpp&时出错头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!