Jump to content

  • Log In with Google      Sign In   
  • Create Account

chiranjivi

Member Since 27 Feb 2010
Offline Last Active Aug 25 2014 02:53 PM

#5046218 Help me understand .cpp vs .h in C++

Posted by chiranjivi on 24 March 2013 - 08:15 AM

Having trouble getting my head around the concept of separating code into .cpp and .h files. I've been coding in C++ for a while now and have never done anything other than just stick all code into header files, which I guess I'm going to have to grow out of eventually.

Here's an example of the problems I'm having. This is the level class for a toy game. From what I have been reading I believe I'm supposed to split it into level.h and level.cpp something like this:

level.h
#ifndef LEVEL_H_INCLUDED
#define LEVEL_H_INCLUDED

class Level {
    public:
    Level();

    int width, height;
    int map_grid[20][20];

    void display_grid();
};

#endif // LEVEL_H_INCLUDED

level.cpp
#include "level.h"

Level::Level() {
    width = height = 20;
    for ( int i = 0; i != width; ++i ) for ( int j = 0; j != height; ++j ) {
        if ( i == 0 || i == width-1 || j == 0 || j == height-1 ) {
            map_grid[j][i] = 1;
        } else {
            map_grid[j][i] = 0;
        }
    }
}

void Level::display_grid() {
    for (int i = 0; i != width; ++i ) for ( int j = 0; j != height; ++j ) {
        if ( map_grid[j][i] == 1 ) draw_sprite( i*64, j*64, block_blue, screen );
    }
}

When I do this, the compiler doesn't like level.cpp, saying 'draw_sprite', 'block_blue' and 'screen' have not been declared. 'draw_sprite' is a function and 'block_blue' and 'screen' are SDL_Surfaces, and they have been declared in an earlier include ("sdl_functions.h"). Attempting to #include sdl_functions.h again at the start of level.cpp prompts the compiler to get angry about me trying to re-declare a load of stuff.

What I don't understand is that if I just mash level.h and level.cpp together into a single header file:

level.h
#ifndef LEVEL_H_INCLUDED
#define LEVEL_H_INCLUDED

class Level {
    public:
    Level();

    int width, height;
    int map_grid[20][20];

    void display_grid();
};

Level::Level() {
    width = height = 20;
    for ( int i = 0; i != width; ++i ) for ( int j = 0; j != height; ++j ) {
        if ( i == 0 || i == width-1 || j == 0 || j == height-1 ) {
            map_grid[j][i] = 1;
        } else {
            map_grid[j][i] = 0;
        }
    }
}

void Level::display_grid() {
    for (int i = 0; i != width; ++i ) for ( int j = 0; j != height; ++j ) {
        if ( map_grid[j][i] == 1 ) draw_sprite( i*64, j*64, block_blue, screen );
    }
}

#endif // LEVEL_H_INCLUDED

...then it works?

Obviously there are huge gaps in my knowledge as to how header and source files are supposed to interact (as well as in many other areas :P), so please go easy on me for asking a very stupid question. Thanks.


PARTNERS