samedi 30 mars 2019

Class definitions in seperate cpp file

I created a new class in c++ with the declarations in the "Bull.h" header file and the corresponding definitions in an extra "Bull.cpp" file just for the class. Now when I try to call a method of that class from my "main.cpp", I get the following error:

Undefined symbols for architecture x86_64:
  "Bull::Bull()", referenced from:
      ___cxx_global_var_init in main-0d8dea.o
  "Bull::intro() const", referenced from:
      _main in main-0d8dea.o
ld: symbol(s) not found for architecture x86_64

I tried to put the method definitions directly in "main.cpp" and it worked fine. I believe, the "Bull.cpp" file with all method defintions is not correctly linked to the header file.

//main.cpp
#include "Bull.h"
#include <iostream>

using FText = std::string;

// Instantiate a new game from Bull class.
Bull BCGame;

int main(void) {
    BCGame.intro();
    return 0;
};

//Bull.h
#include <string>

using FString = std::string;

// Full class of the game.
class Bull {
    public:
        Bull();
        bool is_game_won(void) const;
        int get_current_try(void) const;
        int get_max_tries(void) const;
        int get_word_length(void) const;
        void intro(void) const;
        void reset(void);
        void play_game(void);
        bool play_again(void);
        FString generate_word(int input);
        FString get_guess(void);
    private:
        bool game_state_won;
        int current_try;
        int max_tries;
        const int WORD_LENGTH = 5;
        FString word;
};

//Bull.cpp
#include "Bull.h"
#include <iostream>

using FText = std::string;

// constructor
Bull::Bull(void) {
    reset();
}

void Bull::reset(void) {
    int MAX_TRIES = 10;
    max_tries = MAX_TRIES;
    current_try = 0;
    game_state_won = false;
    return;
}

void Bull::intro(void) const{
    std::cout << "Welcome to Bulls & Cows! \n";
    std::cout << "Guess a " << Bull::WORD_LENGTH << " letter word. For each letter that you got right\n";
    std::cout << "you get a cow. If it's in the right place, you get a bull.\n";
    std::cout << "Now, enter your first guess: ";
    return;
};

...

But I can not find what I am missing to connect both. Hope you guys can help me!

Aucun commentaire:

Enregistrer un commentaire