体系结构的未定义符号x86_64:编译错误

Undefined symbols for architecture x86_64: error of compilation

我有一个 main.cpp 文件,里面有这一行:

#include "Player.hpp"

这里是Player.hpp:

class Player {
 private :
  int type; // [0 = humain local, 1 = IA de niveau 1, 2 = IA de niveau 2, 3 = humain en réseau]
  int score;
  int color;
 public :
  Player();
  Player (int type, int color);

  int getType();
  int getScore();
  int getColor();
};

这里是 Player.cpp :

 Player::Player() {
  }

  Player::Player(int type, int color) {
    this->type = type;
    this->color = color;
    this->score = 0;
  }

  int Player::getType() {
    return this->type;
  }
  int Player::getScore() {
    return this->score;
  }
  int Player::getColor() {
    return this->color;
  } 

如果我用这一行编译:

g++ Main.cpp -o main

它告诉我错误:

Undefined symbols for architecture x86_64:
  "Player::getColor()", referenced from: etc...........

但是,如果我将 Player.cpp 中的代码放在 Player.hpp 中的代码下方,如下所示:

 class Player {
     private :
      int type; // [0 = humain local, 1 = IA de niveau 1, 2 = IA de niveau 2, 3 = humain en réseau]
      int score;
      int color;
     public :
      Player();
      Player (int type, int color);

      int getType();
      int getScore();
      int getColor();
    };

 Player::Player() {
  }

  Player::Player(int type, int color) {
    this->type = type;
    this->color = color;
    this->score = 0;
  }

  int Player::getType() {
    return this->type;
  }
  int Player::getScore() {
    return this->score;
  }
  int Player::getColor() {
    return this->color;
  } 

有效。

我该怎么做才能解决这个问题?我觉得是编译的问题

感谢您的帮助!

Main.cpp 引用了 Player.hpp 但没有引用 Player.cpp。添加行:

#include "Player.cpp"

应该可以解决这个问题

这里是你的命令,

g++ Main.cpp -o main

不编译或 link Player.cpp 文件,所以它正确地说它在 Player.cpp 文件中找不到它正在谈论的符号。

将 Player.cpp 添加到您的构建命令中:

g++ Main.cpp Player.cpp -o main