【问题标题】:C++ / Eclipse undefined reference questionC++/Eclipse 未定义参考问题
【发布时间】:2009-04-19 02:10:35
【问题描述】:

我在 Eclipse/C++ 中显然是链接器错误(“未定义的引用”)遇到了麻烦。下面显示的所有类都可以正常编译,除了一个 PlayGame.cpp,它给出了“未定义的引用”错误(如下所示)。

以下是相关的类和代码片段。

PlayerFactory.h

PlayerFactory.cpp

游戏.h

游戏.cpp

// constructor for game:

Game::Game (const PlayerFactory& factory)

{

       cout << " constructor" << endl;

}

PlayGame.cpp

// start of code for game where error occurs

#include "Game.h"

#include "PlayerFactory.h"

int main() {
   try

   {

      PlayerFactory factory;

      Game game (factory);  <== undefined reference error
      ...

上面一行给出了错误“undefined reference to `Game(PlayerFactory const&)'”

是什么导致了这个错误,如何纠正?

【问题讨论】:

  • 请尝试将您的问题和代码格式设置得更好

标签: c++ linker


【解决方案1】:

class 声明的默认可见性是私有的。所以PlayerPlayerFactory 类的所有成员函数都是private——客户端无法访问。您需要将它们公开。

Player.h

#ifndef PLAYER_H 
#define PLAYER_H
class Player  
{  
public:
   virtual ~Player() {  
       cout << "Player destructor called" << endl;  

   }  
   virtual void Player::PlayerMakeMove(){  
       cout << "make move" << endl;  
   }  


};  
#endif // PLAYER_H

PlayerFactory.h

#ifndef PLAYERFACTORY_H
#define PLAYERFACTORY_H
class PlayerFactory  
{  
public:
   virtual ~PlayerFactory() {  
       cout << "PlayerFactory destructor called" << endl;  
   }  

   virtual std::auto_ptr<Player> PlayerFactory::MakePlayerX() const{  

       return PlayerFactory::MakePlayer('x');  
   }  

   virtual std::auto_ptr<Player> PlayerFactory::MakePlayerO() const{  
       return PlayerFactory::MakePlayer('o');  

   }  

   std::auto_ptr<Player> PlayerFactory::MakePlayer (char letter) const{  
       auto_ptr<Player> pt( new Player() );  
       return pt;  
   }  
};
#endif // PLAYERFACTORY_H

另外,Game::Play() 缺少 return 语句。

Outcome Game::Play() {  
  cout << " play" << endl;  
  return PlayerXWon;
}

根据需要添加所需的标题、前向声明和using 语句(我在这里跳过它们)。

【讨论】:

  • 不具体。也就是说,它是一个托管的 make 项目。这是我需要做的吗?如果是这样,知道怎么做吗?谢谢。
  • makefile 目标中提到的所有cpp 文件吗?或者,即使是 *.cpp 操作也可以。只需确认正在创建与 PlayerFactory 对应的 obj 文件,并且该 obj 已链接到您的主可执行文件。
  • 我只是在 makefile 中四处寻找,但它都是自动生成的引用对象变量的样板代码。从谷歌搜索来看,如果您使用托管 make 选项,Eclipse 似乎会自动在 make 中包含源文件。到目前为止,我一直很幸运。
  • 你能打印出编译器和/或链接器依赖项的列表吗?我猜会有一些 Eclipse IDE 设置来打开它——检查一下。
  • 编译器允许您指定 -I 选项(当前为空白)。并且有一个 -c -fmessage-length=0 链接器指定 g++ 没有选项但有 make 变量。您可以指定库和库搜索路径,现在为空。杂项(链接器标志)为空。共享库设置为空。感谢您的检查。我可能会尝试手动制作。
【解决方案2】:

好吧,无论出于何种原因,链接器都找不到实现 构造函数,这强烈表明它没有被编译。

几个调试步骤:

  • 尝试查找由 gcc 生成的 .obj 文件。看看能不能找到 Game.obj 其中。

  • 找到一种方法让 IDE 输出它为 gcc 生成的命令行

  • 如果没有直接的方法,总会有:

    • 制作脚本,用它替换gcc,让脚本写命令行 放入一个文件并检查它。

【讨论】:

    猜你喜欢
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 2018-08-06
    • 2020-10-18
    • 2013-01-02
    • 1970-01-01
    • 2021-06-02
    相关资源
    最近更新 更多