Jordan Savell
Jordan Savell

Reputation: 27

C++ Headers & Undefined Reference

So I'm just getting to grips with C++ and progressing onto using header files. Thing is, I'm totally confused. I've read a documentation but none to make me understand it well enough.

I'm just making a silly 'game' which is interactive, it will probably be discarded and thought I could practice use on header files. This is my file structure:

   terminal_test
    ├── core.cpp
    └── game
        ├── game.cpp
        └── game.h

Now, here is my core.cpp:

#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "game/game.h"

using namespace std;

void mainMenu();
void rootInterface() {

  cout << "root@system:~# ";

}

int main() {

  system("clear");
  usleep(2000);

  mainMenu();

  return 0;

}

void mainMenu() {

  int menuChoice = 0;

  cout << "[1] - Start Game";
  cout << "[2] - How To Play";
  cout << endl;

  rootInterface();
  cin >> menuChoice;

  if ( menuChoice == 1 ) {

      startGame();

  } else if ( menuChoice == 2 ) {

      cout << "This worked."; 

  }
}

Everything else works fine but startGame(); under my menu choice. When I compile using g++ core.cpp game/game.cpp it bounces back with this error: undefined reference to startGame();. I firstly did some troubleshooting to see if it was properly finding game.h by changing the #include "game/game.h" to something like #include "game.h" without the directory listed inside and it gave me a game.h could not be found so I know it's recognising it, just not compiling at all.

Here is my game.h:

#ifndef GAME_H // Making sure not to include the header multiple times
#define GAME_H
#include "game.h"

void startGame();

#endif

game.cpp:

#include <iostream>
#include <stdio.h>
#include "game.h"

int main(int argc, char const *argv[]) {

  void startGame() {

    cout << "It worked.";

  }

  return 0;
}

My file structure isn't named properly either, I just threw it in because it was something to just get to grips with header files in C++.

So, here are my questions:

1) - What is this error specifically saying and what should I do to fix it?

2) - How do header files communicate and work with other files and is there clear documentation/guides out there that can help?

Upvotes: 2

Views: 1157

Answers (1)

Chad
Chad

Reputation: 19022

Local function definitions are not what you want here:

#include <iostream>
#include <stdio.h>
#include "game.h"

int main(int argc, char const *argv[]) {

  // an attempt to define startGame() inside of main()
  void startGame() {

    cout << "It worked.";

  }

  return 0;
}

main is not needed in your game.cpp file. You should define startGame() outside of main, like this:

#include <iostream>
#include <stdio.h>
#include "game.h"

// definition of startGame
void startGame() {

  cout << "It worked.";

}

Upvotes: 3

Related Questions