0

I try to code a Checkers game.

To make it easier to read, I wanted to split it into several files, but I get an "undefined reference" error. So far, I have a main.cpp, a Board.cpp and a Board.hpp. It works, when its all in main.cpp, but once I split it up, and include the board header file, I get the error.

I have done this before, and it looks just like how I've done it before, so I don't know why it's acting up now.

main.cpp

#include <iostream>
#include <array>
#include <cmath>
#include "Board.hpp"

class Gameplay
{
   protected:
       std::array<std::array<char,8>,8> gameboard;   // Board with tokens on it
   public:
       //....
       //Beginning Set-Up
       void setup ();
       /...

       friend class Board;

};

//SetUp
void Gameplay::setup ()
{
    char user1 = '@';      //Symbol of User 1
    char user2 = 'c';
    Board plainBoard;     //board with no tokens    //These two lines is when I get the undefined
    plainBoard.create();                            //reference error
    gameboard = plainBoard.board;
    //...
}

Board.hpp

#ifndef BOARD_HPP_INCLUDED
#define BOARD_HPP_INCLUDED
#endif // RECHNER_HPP_INCLUDED
#include <iostream>
#include <array>



class Board
{
protected:
    std::array<std::array<char,8>,8> board;    //Plain Board
public:
//....
friend class Gameplay;
};

board.cpp

#include <iostream>
#include <array>
#include <cmath>
#include "Board.hpp"

//...

The code works, I just get the #include part wrong. Errors: undefined reference to 'Board::create()' undefined reference to 'Board::~Board()'

  • You did not show the actual error message, so we can't see which reference is erroring. But on a side note, the contents of `Board.hpp` need to be *inside* the `#ifndef..#define..#endif` header guard, not *underneath* it. – Remy Lebeau Feb 18 '21 at 20:27
  • You need to "link" your main.cpp to the Board symbols. This can be either done by adding the board.cpp after main.cpp in g++ command or by adding a "-lboard" if you already have Board in a separate library – N. Prone Feb 18 '21 at 20:49
  • If you are using VSCode you need to modify your `tasks.json` file if you are using the default configuration. The default builds only the active file into the executable. The documentation will have a section about Modifying tasks.json which explains the change necissary. – drescherjm Feb 18 '21 at 21:39

0 Answers0