[SIMPLE] Splitting up code in different files

Started by
3 comments, last by Emmanuel Deloget 18 years, 10 months ago
Hello everybody, here I am back with another very easy question: I want to write my 'Player' class in a new file called 'player.cpp'. So that's what I did: main.cpp


#include "player.h"


player.cpp


#include "player.h"

class CPlayer
{
	public:
		int		position_x;
		int		position_y;
		int		offset_x;
		int		offset_y;
		int		jump_velocity;
		int		health;
		bool	shooting;

		CSpriteBase		sprite_base;
		CSprite			sprite;

		void DrawHealthbar ( void );
};

player.h


extern CPlayer	player;


This is exactly how my c++ book says it should be done, but it does not work. It always returns 'error C2146: Syntaxerror : Missing ';' before 'player' when I try to use the class (access it) from main.cpp... What am I doing wrong?
Advertisement
Almost

player.hclass CPlayer { stuff };   // Must come before any CPlayer variable definitionextern CPlayer player;     // Must come before any use of playerplayer.cpp#include "player.h"CPlayer player;            // Actually creates the player variable


See Kylotan's organising code files article.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
First of all, place your class declaration in Player.h . Then, place your class implemenation in Player.cpp . You can have the extern CPlayer player; in Player.h , but do it after the class declaration. However, if you're doing that, you must have player declared somewhere else (assumably Player.cpp).

Here's a visual breakdown:

Main.cpp
#include "Player.h"CPlayer player;


Player.h
class CPlayer{	public:		int		position_x;		int		position_y;		int		offset_x;		int		offset_y;		int		jump_velocity;		int		health;		bool	shooting;		CSpriteBase		sprite_base;		CSprite			sprite;		void DrawHealthbar ( void );};extern CPlayer player;


Player.cpp
#include "Player.h"void CPlayer::DrawHealthbar(void){     ...}


Try reading your book again, or get a new book (that one seems bad)..
Hope this helps.
Thanks guys, you are better than ANY book... :)

No, your book don't tell you that. You'll want to check it again carefully.

1) the CPlayer class definition should be in the H file, not in the CPP file.
2) "extern CPlayer player;" should also be in the H file, after the class definition.
3) the CPP file should contain
#include "Player.h"CPlayer player;

4) you'll probably need to add the correct includes to the player.h file - if you don't, then both CSpriteBase and CSprite will be undefined, and your code will not compile.

There is an article somewhere on gamedev.net that deal with code management - the C++ "where to put why". Hélas I'm unable to find it tonight.

I'm incredibly slow. The article I cited is Kylotan's one, of course.

HTH

This topic is closed to new replies.

Advertisement