我是c++的新手程序员,目前遇到编译错误
Undefined symbols for architecture x86_64
据推测,这源于头文件和实现文件的包含/编码方式。
下面是一些生成我收到的编译错误的代码
主要
//Main.cpp
#include <iostream>
#include <string>
#include "Animal.hpp"
using namespace std;
int main(){
Animal myPet;
myPet.shout();
return 0;
}
标题
//Animal.hpp
#ifndef H_Animal
#define H_Animal
using namespace std;
#include <string>
class Animal{
public:
Animal();
void shout();
private:
string roar;
};
#endif
实现
//Animal.cpp
#include "Animal.hpp"
#include <string>
Animal::Animal(){
roar = "...";
}
void Animal::shout(){
roar = "ROAR";
cout << roar;
}
这段代码产生了我的编译问题。如何解决这个问题?
谢谢你的时间
编辑
Undefined symbols for architecture x86_64:
"Animal::shout()", referenced from:
_main in test-5f7f84.o
"Animal::Animal()", referenced from:
_main in test-5f7f84.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
最佳答案
也许您可能想查看另外一组 3 个文件,其中的内容更加“有序”,您知道,内容被放置在它们“真正”属于的地方。
所以这是"new"头文件..
//Animal.hpp
#ifndef H_Animal
#define H_Animal
#include <string> // suffices
// Interface.
class Animal {
std::string roar; // private
public:
Animal();
void shout();
};
#endif
然后是源文件..
//Animal.cpp
#include "Animal.hpp"
#include <iostream> // suffices
// Constructor.
Animal::Animal()
:
roar("...") // data member initializer
{}
// Member function.
void Animal::shout() {
roar = "ROAR";
std::cout << roar;
}
和主程序..
//Main.cpp
#include "Animal.hpp"
int main(){
Animal thePet;
thePet.shout(); // outputs: `ROAR'
}
加上一点 GNU makefile ..
all: default run
default: Animal.cpp Main.cpp
g++ -o Main.exe Animal.cpp Main.cpp
run:
./Main.exe
clean:
$(RM) *.o *.exe
在您的 cmd 行中输入“make”即可启动。你喜欢它吗? -- 问候,M.
关于c++ - 如何正确包含头文件和实现文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31886595/