Martijn Courteaux
Martijn Courteaux

Reputation: 68857

C++: Maybe you know this pitfall?

I'm developing a game. I have a header GameSystem (just methods like the game loop, no class) with two variables:
int mouseX and int mouseY. These are updated in my game loop. Now I want to access them from Game.cpp file (a class built by a header-file and the source-file). So, I #include "GameSystem.h" in Game.h. After doing this I get a lot of compile errors. When I remove the include he says of course:

Game.cpp:33: error: ‘mouseX’ was not declared in this scope
Game.cpp:34: error: ‘mouseY’ was not declared in this scope

Where I want to access mouseX and mouseY.

All my .h files have Header Guards, generated by Eclipse.
I'm using SDL and if I remove the lines that wants to access the variables, everything compiles and run perfectly (*).

I hope you can help me...

This is the error-log when I #include "GameSystem.h" (All the code he is refering to works, like explained by the (*)):

In file included from ../trunk/source/domein/Game.h:14,
                 from ../trunk/source/domein/Game.cpp:8:
../trunk/source/domein/GameSystem.h:30: error: expected constructor, destructor, or type conversion before ‘*’ token
../trunk/source/domein/GameSystem.h:46: error: variable or field ‘InitGame’ declared void
../trunk/source/domein/GameSystem.h:46: error: ‘Game’ was not declared in this scope
../trunk/source/domein/GameSystem.h:46: error: ‘g’ was not declared in this scope
../trunk/source/domein/GameSystem.h:46: error: expected primary-expression before ‘char’
../trunk/source/domein/GameSystem.h:46: error: expected primary-expression before ‘bool’
../trunk/source/domein/FPS.h:46: warning: ‘void FPS_SleepMilliseconds(int)’ defined but not used

This is the code which try to access the two variables:

SDL_Rect pointer;
pointer.x = mouseX;
pointer.y = mouseY;
pointer.w = 3;
pointer.h = 3;
SDL_FillRect(buffer, &pointer, 0xFF0000);

Upvotes: 0

Views: 327

Answers (1)

Amardeep AC9MF
Amardeep AC9MF

Reputation: 19044

In your GameSystem header, don't define those variables as:

int mouseX;
int mouseY;

instead, you should declare them:

extern int mouseX;
extern int mouseY;

Then in one of your .cpp files you define them:

int mouseX;
int mouseY;

The problem with defining them in a header file is that the compiler will try to instantiate them in every single .cpp where you include the header.

Upvotes: 4

Related Questions