Jack BeNimble
Jack BeNimble

Reputation: 36673

C++ / Eclipse undefined reference question

I'm having trouble with what is apparently a linker error ("undefined reference") in Eclipse / C++. All the classes shown below compile fine, except for one, PlayGame.cpp, which is giving the "undefined reference" error (also shown below).

Below are the relevant classes and pieces of code.

PlayerFactory.h

PlayerFactory.cpp

Game.h

Game.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
      ...

The above line gives the error "undefined reference to `Game(PlayerFactory const&)'"

What's causing this error, and how can it be corrected?

Upvotes: 0

Views: 5967

Answers (2)

dirkgently
dirkgently

Reputation: 111150

The default visibility for class declarations is private. So all the member functions of both Player and PlayerFactory classes are private -- not accessible by clients. You need to make them public.

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

Also, the Game::Play() lacks a return statement.

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

Do add the required headers, forward declarations and using statements as required (I skip them here).

Upvotes: 1

AndreasT
AndreasT

Reputation: 9801

Well, for whatever reason, the linker doesn't find the implementation of the constructor, which strongly suggests that it doesn't get compiled.

A Few debugging steps:

  • try to find the .obj files that get generated by gcc. See if you can find Game.obj among them.

  • Find a way to get the IDE to output the command line it generates for gcc

  • if there's no straightforward way, there's always:

    • Make a script, replace gcc with it, and make the script write the commandline into a file and examine that.

Upvotes: 1

Related Questions