【问题标题】:error when compiling - linking .cpp & header file编译时出错 - 链接 .cpp 和头文件
【发布时间】:2018-09-10 01:44:43
【问题描述】:

我正在尝试将我的 .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 */

我应该怎么做才能修复这个错误?随意添加我可以做的任何其他事情来改进我刚刚编写的代码。对任何事物开放。

【问题讨论】:

    标签: c++ macos terminal header implementation


    【解决方案1】:

    下面是一本很好的读物,可以帮助您了解尝试从源代码创建可执行文件时发生的情况:How does the compilation/linking process work?

    这里发生的情况是,链接器不知道在main() 中调用的Person::Person() 位于何处。请注意,当您调用 g++ 时,您从未将您为 Person::Person() 编写代码的文件提供给它。

    调用g++的正确方式是: $ g++ -o main main.cpp person.cpp

    【讨论】:

      【解决方案2】:

      链接错误表示链接找不到构造函数。构造函数不在 main.cpp 中,它在您的其他文件中,在您的示例中未命名。尝试将所有这些都放在一个 cpp 文件中以使其正常工作。

      【讨论】:

        猜你喜欢
        • 2012-08-30
        • 1970-01-01
        • 2013-09-04
        • 2021-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多