c++ - 如何正确包含头文件和实现文件?

标签 c++ header-files

我是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/

相关文章:

c++ - 如何正确评论

c++ - 如何在 C++ 中创建两个相互用作数据的类?

c++ - 堆上的用户定义变量在 while 循环中被销毁

c++ - 将 long double 转换为 CString

c - C 中的一次性伪通用 header

c++ - 在多个 Cpp 文件中使用一个变量

c++ - 如何找到从哪里导入 C++ 程序中的特定函数?

c++ - 为什么c++ std::hash会创建一个仿函数结构体并且可以在每次不创建结构体的情况下调用它

c++ - C++ 中的数组指针

c++ - 使用 string::find_first_not_of 和 string::find_last_not_of 的问题