C++: Maybe you know this pitfall? - c++

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);

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.

Related

Typedef not a member of namespace

So, I'm attempting to fork some open source code and upon compilation I am greeted with these errors:
C2039 'TransactionId': is not a member of 'CryptoNote'
C2061 syntax error: identifier 'TransactionId'
I'm relatively inexperienced with C++ usually confining myself to the realms of C#, however, I can clearly see that TransactionId is a typedef declared in a different file like so:
namespace CryptoNote {
typedef size_t TransactionId;
typedef size_t TransferId;
//more code
And the line throwing the error is:
void sendTransactionCompleted(CryptoNote::TransactionId _id, bool _error, const QString& _error_text);
To my inexperienced eyes, that looks as though TransactionID is definitly a member of Cryptonote is it not?
Any ideas what's going on?
The repo is here: https://github.com/hughesjs/Incendium_GUI
And the necessary submodule is here: https://github.com/hughesjs/Incendium_Crypt
Those typedefs are defined in Incendium_Crypt/include/IWalletLegacy.h.
void sendTransactionCompleted(CryptoNote::TransactionId _id, bool _error, const QString& _error_text);`
is defined in Incendium_GUI/src/gui/SendFrame.h, which includes IWallet.h. However, IWallet.h does not in turn include IWalletLegacy.h. Hence, those typedefs are unknown to SendFrame.h.
It's difficult to say without seeing all the code but a few things come to mind:
Firstly is this the first error you get. Compilation errors with C++ tend to result in a bunch of secondary errors. For example the following results in a similar error to what you see but fails to compile because size_t has not been defined:
namespace CryptoNote {
typedef size_t TransactionId;
typedef size_t TransferId;
}
int main(void)
{
CryptoNote::TransactionId id;
return 0;
}
$ g++ -std=c++11 namespace.cxx -o namespace
namespace.cxx:4:9: error: ‘size_t’ does not name a type
typedef size_t TransactionId;
^~~~~~
namespace.cxx:5:9: error: ‘size_t’ does not name a type
typedef size_t TransferId;
^~~~~~
namespace.cxx: In function ‘int main()’:
namespace.cxx:11:17: error: ‘TransactionId’ is not a member of ‘CryptoNote’
CryptoNote::TransactionId id;
^~~~~~~~~~~~~
See http://www.cplusplus.com/reference/cstring/size_t/ for a list of headers that define size_t.
Is CryptoNote nested inside another namespace?
Is there another CryptoNote defined in the namespace your function is declared in?
Are these in the same header file? If not, is the header file where the namespace is defined included in the header file containing the function declaration?

I'm trying to dynamically allocate for static byte board[67] in a class

This line of code from this first of two .cpp files
static byte board[64+3]; ... more code //board array of 67 is declared here
board is used in here
if ((board[FR(move)] == WHITE_PAWN && R(TO(move)) == RANK_8)
and further more in the code.
I'm trying to convert this into more of a object oriented program. First I'm trying to allocate for board in another .h and .cpp file
This is my board.h file
class Board
{
public:
Board();
private:
};
This is my other.cpp file
Board::Board()
{
byte *board =new byte[67];
}
this is the error I get
mscp.cpp: In function ‘int search(int, int, int)’:
mscp.cpp:1649:26: error: ‘board’ was not declared in this scope
for (i=ply-4; i>=board[LAST]; i-=2) {
^
board.cpp: In constructor ‘Board::Board()’:
board.cpp:7:2: error: ‘byte’ was not declared in this scope
byte board =new byte[67];
^
board.cpp:7:7: error: expected ‘;’ before ‘board’
byte board =new byte[67];
Why can't my first .cpp file see board?
One of numerous errors here is that you have declared board to be a local variable in your constructor only. You need to make that a public member of the class Board if you want visibility outside your class.
PS: You are probably currently going to leak memory as well, even after sorting the other issues out! As you are not de-allocating the heap space you allocated at the end of your constructor when board goes out of scope.

forward declaration problems

I think I am having a problem with forward declarations. I think one is necessary, but I'm not sure.
Basically I have a main.cpp:
//main.cpp
#include <iostream>
#include "CalculateForces.h"
#include "ParticleBox.h"
int main(void)
{
//g++ main.cpp ParticleBox.cpp -lgsl -lgslcblas -lm -std=c++0x
CalculateForces* calculate_forces= new CalculateForces();
ParticleBox* particles_box = new ParticleBox(2000,100,100,100);
delete calculate_forces;
delete particles_box;
return 0;
}
CalculateForces.h looks like this:
//CalculateForces.h
//We update the forces on each particle
class ParticleBox;
class CalculateForces
{
public:
CalculateForces(void);
~CalculateForces(void);
int UpdateForces(ParticleBox* particlebox);
int DiscretizeSpace(float cutoff_distance);
int LJForce(int local_index, int remote_index, ParticleBox* particlebox);
};
And finally the ParticleBox.h File looks like this:
//ParticleBox.h
//This is the definition of the particlebox. We manage all the particles in this
//file
//This should be changed to a template so that we can run float and double calcs properly :D
struct Particle;
class ParticleBox
{
public:
ParticleBox(int Num_Particles, float Box_length_x_, float Box_length_y_, float Box_length_z_);
~ParticleBox(void);
int set_num_particles(int Num_Particles);
int InitialiseUniverse(int temp,float mass);
float Boltzmann(float temperature);
int GenerateRandomUniquePositions(int number, float max, float min, float* rand_dim_positions);
private:
//Array to hold particles. Each particle has its own struct
Particle** particle_list_;
int num_particles_;
float box_length_x_;
float box_length_y_;
float box_length_z_;
float* rand_x_positions_;
float* rand_y_positions_;
float* rand_z_positions_;
float cutoff_distance_;
float sigma_;
float epsilon_;
};
int CalculateForces::DiscretizeSpace(float cutoff_distance, ParticleBox* particlebox)
{
......
return 0;
}
I use a forward declaration in ParticleBox.h of the Particle Struct and I can add a pointer of type Particle* to the class. This works fine.
The forward in CalculateForces.h of Class ParticleBox causes loads of compiler errors (too many to post but they start in an identical way to the below). Omitting it produces only a few errors:
In file included from main.cpp:3:0:
CalculateForces.h:9:20: error: ‘ParticleBox’ has not been declared
CalculateForces.h:11:50: error: ‘ParticleBox’ has not been declared
In file included from CalculateForces.cpp:3:0:
CalculateForces.h:9:20: error: ‘ParticleBox’ has not been declared
CalculateForces.h:11:50: error: ‘ParticleBox’ has not been declared
CalculateForces.cpp:12:35: error: ‘int CalculateForces::UpdateForces’ is not a static member of ‘class CalculateForces’
CalculateForces.cpp:12:35: error: ‘ParticleBox’ was not declared in this scope
CalculateForces.cpp:12:48: error: ‘particlebox’ was not declared in this scope
CalculateForces.cpp:13:1: error: expected ‘,’ or ‘;’ before ‘{’ token
I thought i would need the forward declaration as I try to use that type as an argument? What am i doing wrong?
Thanks and sorry for the long post
Your post is quite confusing because you posted the error that show up when you omit the forward declaration and you obviously have some additional errors in your code that mix with the error you asked about.
I assume that with the forward declaration, the errors change as they appear mostly in the implementation files, right? In this case the problem might be that the forward declaration is enough as long as you declare a pointer to the type, but it is not enough when you start using the pointer (dereferencing it).
If that is the case, the problem is most likely that you forgot to #include "ParticleBox.h" in CalculateForces.cpp (or some other implementation files).
As Rob determined the source of the errors was in a bit of code that I did not post. There were a few errors but the biggest was that in CalculateForces.cpp I tried to access int num_particles_; which is of course a private member of ParticleBox.

I am having issues with my heading in my function.cpp file

I have one .h which has the class in it and two .cpp, One being the main and the other holding the functions.
My complier is giving me theses errors
Functions.cpp: In member function âvoid Flandre::add()â:
Functions.cpp:10:3: error: âcinâ was not declared in this scope
Functions.cpp:12:33: error: âstrlenâ was not declared in this scope
Functions.cpp:16:6: error: âcoutâ was not declared in this scope
Functions.cpp:16:57: error: âendlâ was not declared in this scope
Functions.cpp:21:7: error: âcoutâ was not declared in this scope
Functions.cpp:21:53: error: âendlâ was not declared in this scope
Functions.cpp:27:9: error: name lookup of âiâ changed for ISO âforâ scoping [-f
Functions.cpp:27:9: note: (if you use â-fpermissiveâ G++ will accept your code)
Functions.cpp:27:16: error: âKYUUâ was not declared in this scope
Functions.cpp:32:6: error: âcoutâ was not declared in this scope
Functions.cpp:32:57: error: âendlâ was not declared in this scope
Functions.cpp:35:17: error: expected primary-expression before â[â token
Functions.cpp:37:14: error: expected unqualified-id before â[â token
Functions.cpp:38:14: error: expected unqualified-id before â[â token
Functions.cpp:39:14: error: expected unqualified-id before â[â token
I think it has something to do with the #include header in Functions
Newprogram2.cpp
>#include <iostream>
#include <string>
#include "newprogram2.h"
Functions.cpp
Some parts are missing but I just want it to complied so I can get add() to work first.
#include "newprogram2.h"
newprogram2.h
#ifndef NEWPROGRAM2_H
#define NEWPROGRAM2_H
#include<string>
using namespace std;
#endif
You have to include the proper headers for the functions you want to use.
For cin, cout and endl you need to #include <iostream>, you forgot to do that in your 2nd .cpp file
The compiler doesn't recognize strlen as a function because it is not in <string> (see http://www.cplusplus.com/reference/string/) but in <string.h> (see http://www.cplusplus.com/reference/cstring/strlen/).
I suggest you use either size() or length(), these are in <string>, both of these can be called on std::string objects.
Functions.cpp:27:16: error: âKYUUâ was not declared in this scope
This error shows because you try to access a variable you declared in another .cpp file. The .cpp file you are trying to access it in doesn't know this variable. You can fix that by moving the variable into the header file.
Functions.cpp:27:9: error: name lookup of âiâ changed for ISO âforâ scoping
This can be fixed by changing this
for(i=0;i<=KYUU;i++)
to this
for(int i=0;i<=KYUU;i++)
Functions.cpp:35:17: error: expected primary-expression before â[â token
Functions.cpp:37:14: error: expected unqualified-id before â[â token
Functions.cpp:38:14: error: expected unqualified-id before â[â token
Functions.cpp:39:14: error: expected unqualified-id before â[â token
These errors show because you try to call functions directly on a class instead of an object instantiated from that class, like this Flandre[i].getid(). You cannot do that, make an object instead and call the functions on the object.

C++ trying to use #ifndef and #include statements

Ok, so I'm a HTML/Javascript/PHP professional, but I'm trying to learn C++. I'm still a newbie at it, and I have a C++ programming project that I have errors with.
The file that contains int main() is 'football.cpp', and I have .h and .cpp files for three classes that I have to use: Game, Team, and Date. Each instance of Team contains a vector of Games, and each Game contains a Date. Date does not contain instances of any other class.
I am trying to find a way to use #include and #ifndef statements at the tops of the files so that I don't get errors when I compile, but I haven't found a combination that works. I am not sure if there are other bugs. Here's my current #include sections, not counting other libraries:
football.cpp
#include "game.h"
#include "team.h"
#include "date.h"
team.h
#ifndef __game_h_
#define __game_h_
#endif
team.cpp
#include "team.h"
#ifndef __game_h_
#define __game_h_
#endif
game.h
#ifndef __date_h_
#define __date_h_
#endif
game.cpp
#include "game.h"
#ifndef __date_h_
#define __date_h_
#endif
date.cpp
#include "date.h"
I use Cygwin g++ compiler, and the line I use to compile it is:
g++ football.cpp team.cpp game.cpp date.cpp -o football.exe
Here are all the errors I get: (WARNING, WALL OF TEXT)
$ g++ football.cpp team.cpp game.cpp date.cpp -o football.exe
In file included from football.cpp:9:0:
game.h:15:96: error: ‘Date’ has not been declared
game.h:24:1: error: ‘Date’ does not name a type
game.h:37:1: error: ‘Date’ does not name a type
football.cpp: In function ‘int main(int, char*)’:
football.cpp:65:70: error: no matching function for call to ‘Game::Game(std::string&, std::string&, int [5], int [5], Date&)’
game.h:15:1: note: candidates are: Game::Game(std::string, std::string, const int, const int*, int)
game.h:14:1: note: Game::Game()
game.h:10:12: note: Game::Game(const Game&)
In file included from team.cpp:4:0:
team.h:24:8: error: ‘Game’ was not declared in this scope
team.h:24:12: error: template argument 1 is invalid
team.h:24:12: error: template argument 2 is invalid
team.cpp: In member function ‘float Team::getStat3()’:
team.cpp:36:26: error: request for member ‘size’ in ‘((Team*)this)->Team::games’, which is of non-class type ‘int’
team.cpp:37:21: error: invalid types ‘int[int]’ for array subscript
team.cpp:37:50: error: invalid types ‘int[int]’ for array subscript
team.cpp:38:21: error: invalid types ‘int[int]’ for array subscript
team.cpp:38:47: error: invalid types ‘int[int]’ for array subscript
team.cpp:38:76: error: invalid types ‘int[int]’ for array subscript
team.cpp:38:106: error: invalid types ‘int[int]’ for array subscript
team.cpp: In function ‘bool compare2(Team, Team)’:
team.cpp:45:39: error: request for member ‘size’ in ‘t1.Team::games’, which is of non-class type ‘const int’
team.cpp:46:39: error: request for member ‘size’ in ‘t2.Team::games’, which is of non-class type ‘const int’
team.cpp:50:17: error: request for member ‘size’ in ‘t1.Team::games’, which is of non-class type ‘const int’
team.cpp:50:35: error: request for member ‘size’ in ‘t2.Team::games’, which is of non-class type ‘const int’
team.cpp:52:24: error: request for member ‘size’ in ‘t1.Team::games’, which is of non-class type ‘const int’
team.cpp:52:43: error: request for member ‘size’ in ‘t2.Team::games’, which is of non-class type ‘const int’
team.cpp: In function ‘bool compare3(Team, Team)’:
team.cpp:62:29: error: passing ‘const Team’ as ‘this’ argument of ‘float Team::getStat3()’ discards qualifiers
team.cpp:63:29: error: passing ‘const Team’ as ‘this’ argument of ‘float Team::getStat3()’ discards qualifiers
In file included from game.cpp:5:0:
game.h:15:96: error: ‘Date’ has not been declared
game.h:24:1: error: ‘Date’ does not name a type
game.h:37:1: error: ‘Date’ does not name a type
game.cpp: In constructor ‘Game::Game()’:
game.cpp:26:3: error: ‘date’ was not declared in this scope
game.cpp:26:15: error: ‘Date’ was not declared in this scope
game.cpp: At global scope:
game.cpp:29:94: error: ‘Date’ has not been declared
game.cpp:29:1: error: prototype for ‘Game::Game(std::string, std::string, int*, int*, int)’ does not match any in class ‘Game’
game.h:10:12: error: candidates are: Game::Game(const Game&)
game.h:15:1: error: Game::Game(std::string, std::string, const int*, const int*, int)
game.cpp:13:1: error: Game::Game()
game.cpp: In member function ‘int Game::getVisitingScore(int) const’:
game.cpp:80:10: error: ‘visitingScores’ was not declared in this scope
game.cpp: At global scope:
game.cpp:94:1: error: ‘Date’ does not name a type
Will edit if further clarification is needed, although I don't think it will be.
Any help would be vastly appreciated.
I think that you're misunderstanding the use of include guards.
#ifndef __game_h_
#define __game_h_
// ...
#endif
The set of statements above would typically be used only in the header file describing your game interface, to prevent multiple-inclusion of that header file.
But in your code, you've added include guards to header and implementation, and also you seem to be confusing entities - unless I'm misunderstanding your file contents - for instance in team.h, you have what appear to be include guards for game.
My guess is that your misuse of include guards is actually preventing some types from being defined at all.
As others have mentioned, don't use names beginning with double underscores.
As an example, add include guards to your team header to prevent multiple-inclusion of that file, and give the include guards a name that reflects the module that they're guarding:
// team.h
#ifndef TEAM_H
#define TEAM_H
// ... code for team.h in here
#endif // TEAM_H
It looks like you have 2 problems here: The first is that you are using include guards in your source files; the second is that the order in which you have included your files is wrong.
First, include guards. Others have answered this question already, so I'll be brief. Include guards are used only in header files in order to prevent classes/types being declared more than once. For example if I had:
"game.h":
class Game {};
"game.cpp":
#include "game.h"
#include "game.h" // ERROR: class Game is declared twice.
To fix this I would use include guards in "game.h":
#ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
class Game {};
#endif
The first time the file is included, GAME_H_INCLUDED is not defined, so Game is declared. The second time it is include, GAME_H_INCLUDED is defined, so the declaration is skipped.
The problem you have is that your include guards in you source files will cause all of the implementation to be skipped:
broken "game.cpp":
#include "game.h"
#ifndef GAME_H_INCLUDED // This is defined in "game.h" so everything will be
// skipped until #endif is encountered.
#define GAME_H_INCLUDED
// Implementation of Game class
#endif
Second, the order in which you are including headers is incorrect. I'm guessing you have something like this:
"game.h"
#ifndef GAME
#define GAME
class Game
{
Date mDate; // Member of type Date, declared in "date.h"
};
#endif
"date.h"
#ifndef GAME
#define GAME
class Date
{
};
#endif
"game.cpp"
#include "game.h" // ERROR: Game relies on the Date class,
// which isn't included yet
#include "date.h"
To fix this either swap the order of the includes in "game.cpp":
"game.cpp"
#include "date.h"
#include "game.h" // Fine, we know what a Date is now.
Or include "date.h" in "game.h":
"game.h"
#include "date.h"
#ifndef GAME
#define GAME
class Game
{
Date mDate; // Member of type Date, declared in "date.h"
};
#endif
"game.cpp"
#include "game.h" // Still fine, "date.h" is included by "game.h"
you don't need the guards in your c++ files
The error is that you should use include guards only in your header files
If you have a
BaseClass.h
struct HumanEntity { }
and then have different classes use that base class, without the include guard you may run into issues. That is why you put a
#ifndef __MYGUARD
#define __MYGUARD
... // here is your header code
#endif