XBM XBM - 10 days ago 8
C++ Question

What is a better way of including header files in a C++ code?

This is a console based Maze Game. The idea is to write the game class in a header file and use the class in the main thread. I am not sure if I am doing it right because I get an error. How would I include a header file in my code?

I am using Cloud9 so I don't know if there is a difference between Cloud9 and application software IDE. I am very new to C++, only been using it for some weeks (3-4), so I would like to know if what I am doing it right.

Here is how my code is structured:

This is MazeGame.h:

#ifndef MAZEGAME_H
#define MAZEGAME_H

class Maze{
protected:
int width;
int height;
std::string maze;

public:
Maze(int width, int height){
this->width = width;
this->height = height;
}

static void setMazeBlock(std::string value){
this->maze += value;
}

void destroyMazeBlock(int set){
this->maze[set] -= this->maze[set];
}

std::string getMazeDrawing(){
return this->maze;
}

void setMazeDrawing(std::string val){
this->maze = val;
}

void drawMaze(int times = 1){

for(int i = 0; i <= times; ++i){
std::cout << this->maze;
}
}

void generate(){
for(int i = 0; i < this->width; ++i){
this->setMazeBlock("#");
}
this->setMazeBlock(std::endl);
for(int i = 0; i < this->width; ++i){
this->setMazeBlock("#");
for(int j = 0; j < this->height; ++j){
this->setMazeBlock(std::endl);
if(j == this->width){
this->setMazeBlock("#");
}
}
}
for(int i = 0; i < this->width; ++i){
this->setMazeBlock("#");
}
this->setMazeBlock(std::endl);
}
};


This is MazeGame.cpp:

#include <iostream>
#include <MazeGame.h>

int main(){
Maze m = new Maze(16, 16);

return 0;

}


Both files are in the same directory. However, I am getting this error on the console:

/home/ubuntu/workspace/Maze/MazeGame.cpp:4:22: fatal error: MazeGame.h: No such file or directory
#include <MazeGame.h>
^

Answer

Since your header file is user-defined, you should declare it with double quotes:

#include "MazeGame.h"

The way you were trying to declare it is the method you would use for built-in headers. For example:

#include <iostream>
Comments