编译时出错 - 链接.cpp和头文件

问题描述 投票:1回答:2

我正在尝试将我的.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
2个回答
1
投票

这是一个很好的阅读,以了解当您尝试从源代码创建可执行文件时发生了什么:How does the compilation/linking process work?

这里发生的是链接器不知道在Person::Person()中调用的main()位于何处。请注意,当你调用g ++时,你从来没有给它写过为Person::Person()编写代码的文件。

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.