Public Group

# [SIMPLE] Splitting up code in different files

This topic is 4725 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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?

##### Share on other sites
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.

##### Share on other sites
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){     ...}

Hope this helps.

##### Share on other sites
Thanks guys, you are better than ANY book... :)

##### Share on other sites

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

• 16
• 9
• 13
• 41
• 15