Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This class below is causing a horrendous amount of errors. It appears to be fine though. Any C++ Gurus around who know why VC++ hates me?
Entity.h
#pragma once
#include "World.h"
#include "Renderer.h"
class Entity {
public:
Entity(World* world, Coordinate coord);
~Entity();
void render(Renderer renderer) const;
World* world;
Coordinate coord;
};
Entity.cpp
#include "Entity.h"
Entity::Entity(World* world, Coordinate coord) : world(world), coord(coord) {
world->entities.insert(this);
}
Entity::~Entity() {
world->entities.erase(this);
}
The errors themselves don't make a whole lot of sense as they aren't even related to this file. Some of the common errors are unexpected end of file, missing ';' before '{' and "Entity is not a class or namespace name". Those errors do not occur when I do not include Entity in my project. The last of those errors appear in the declaration code of Entity.
The errors (With all duplicates removed): http://pastebin.com/TEMEhVZV
World.h
#pragma once
#include <map>
#include <vector>
#include <unordered_set>
#include "Chunk.h"
#include "Coordinate.h"
#include "Renderer.h"
class World {
public:
~World();
void generateChunk(Coordinate coord);
void loadChunk(Coordinate coord);
void renderWorld(Renderer* renderer);
std::unordered_set<Entity*> entities;
inline Chunk* getChunk(Coordinate coord) const {
return loadedChunks.at(coord);
}
private:
std::map<Coordinate, Chunk*> loadedChunks;
};
Renderer.h
#pragma once
#include <SFML/Window.hpp>
#include <SFML/OpenGL.hpp>
#include "World.h"
class Renderer {
public:
sf::Window *window;
void bind(sf::Window* newWindow);
void initializeOpenGL();
void renderChunk(Chunk* chunk);
inline void drawPoint(Coordinate coord) {
glBegin(GL_POINTS);
glVertex3d(coord.x, coord.y, coord.z);
glEnd();
}
private:
template <class T>
inline static void pushVector3(std::vector<T>* vertices, T x, T y, T z);
};
To me, it looks like a circular header dependency, meaning something can't be defined.
If your Renderer.h file has a method acting upon an Entity object, and contains this header file as a dependency, Entity will have to be declared before Renderer can be compiled. (The compiler needs to know how big an Entity object will be so it can hard-code the stack offset.)
But similarly, Renderer needs Entity. So it can't be compiled, either!
This may not have shown up in your project before, because the header files are loaded in a different order than now, when the 'Entity' header triggers them.
So, what you should do is modify the headers so there are no circular dependencies, and then reference only pointers in the header, since they have fixed, known sizes. Here are some tricks:
Include low-level classes instead of higher ones.
#include "World.h"
-->
#include "Coordinate.h"
class World;
Use pointers.
#include "Renderer.h"
void render(Renderer renderer) const;
-->
class Renderer;
void render(Renderer* renderer) const;
Doing these, the header files can be moved to your .cpp file:
#include "Entity.h"
#include "World.h"
#include "Renderer.h"
Try going to the very first error its spits out, and fixing that one. In VC++ double-clicking there should take you to the line in question. Often times after the first error or two the compiler is so hopelessly confused that nothing else in its output is worth looking at.
My suspicion would be that it will take you to a line in one of those header files you are not displaying.
It's hard to give too much help without more context. In my experience, errors like this almost always relate to a missing semicolon. Are you given a file and line number with those errors? I would check in Renderer.h, and make sure it is not missing a semicolon.
The reason I suggest this is because, when you #include a file, the compiler actually copies it in to this file. That means that typos in previous files can manifest themselves in these files. If you can post more information, or even copy and paste the errors themselves, I'll try to be more helpful.
EDIT:
Since you've posted your errors, this makes much more sense. If you look, the first error in the list is actually number 148. You have to scroll down for error number 1:
"Error 1 error C2065: 'Entity' : undeclared identifier world.h"
To me, this looks like you're trying to use the class Entity in the file world.h, and it doesn't exist yet. So this looks like a circular include problem.
Related
I'm having some troubles where a function isn't returning the right type, because a class isn't defined. I'm using a factory pattern.
The two error messages that I'm getting are:
'return': cannot convert from 'DLA *' to 'Layer *'
and:
'Layer': base class undefined (compiling source file src\Layer.cpp)
and this same error message is repeated for every file that includes Layer.h.
Here is what my class that inherits from Layer looks like (DLA.h):
#pragma once
#ifndef _DLA
#define _DLA
#include "ofMain.h"
#include "ofxGui.h"
#include "Layer.h"
class DLA: public Layer
{
public:
DLA();
void setup();
void update();
void draw();
private:
};
#endif
and here is my Layer class header (Layer.h):
#pragma once
#ifndef _LAYER
#define _LAYER
#include "ofMain.h"
#include "ofxGui.h"
#include "DLA.h"
enum SceneType
{
Scene_None,
Scene_Default,
Scene_DLA,
};
class Layer
{
public:
void setup();
void update();
void draw();
static Layer *CreateSimulation(SceneType Type);
private:
};
#endif
The function which is failing is this one, situated in Layer.cpp:
Layer *Layer::CreateSimulation(SceneType Type)
{
switch (Type)
{
case Scene_None:
default:
return nullptr;
case Scene_DLA:
return new DLA();
}
}
I've tried everything I could find on Stack Overflow that had similar issues to mine but I've seen some people recommend very subtle code indentation to fix this, so I'm really lost as to find where the problem is.
As they stand, your header files induce circular dependency, even though the #pragma once (and other) guards prevent any actual 'infinite recursion'. Let's look at the sequence of code, from the compiler's point-of-view, when compiling the Layer.cpp file (or any other '.cpp' source that has #include "Layer.h" in it).
The compiler encounters #include "Layer.h" (the first time it has done so - the guards won't be 'triggered'), so it duly replaces that line with the contents of the indicated header. In that content, it encounters #include "DLA.h" (we can ignore the other headers included in this discussion, assuming that they aren't relevant to the problem in hand). So, it then duly replaces that line with the contents of the DLA.h header, at which point it will come across this:
#include "Layer.h"
class DLA: public Layer
{
Now, here, when it replaces #include "Layer.h" with the header content, that content will be 'empty' (because of the guards, as it has already included that header once). Thus, when the public Layer code is encountered, it is an error, because that class has not yet been defined, or even declared as a class.
So, if you really insist on having the #include "DLA.h" line in Layer.h, then it must be placed after the definition of the Layer class.
However, a far better way would be to remove #include "DLA.h" from Layer.h, and only place it in source (.cpp) files that actually need it (like Layer.cpp). This would work well:
// Layer.cpp
#include "Layer.h"
#include "DLA.h" // At this point, references to the Layer class in DLA.h will be fine!
//...
Layer *Layer::CreateSimulation(SceneType Type)
{
switch (Type)
{
case Scene_None:
default:
return nullptr;
case Scene_DLA:
return new DLA();
}
}
Feel free to as k for any further clarification and/or explanation.
I have three classes.
first class:
#ifndef C_LINKED_LIST_H
#define C_LINKED_LIST_H
class CLinkedList {
private:
//removed code for brevity
public:
// removed code for brevity
};
#endif
second class:
#ifndef C_SSF_FOLDER_CONTAINER_H
#define C_SSF_FOLDER_CONTAINER_H
#include "C_SSF_Folder.h"
#include "CLinkedList.h"
class C_SSF_Folder_Container {
private:
// removed code for brevity
public:
int Add_Folder(C_SSF_Folder *_pcl_SSF_Folder);
C_SSF_Folder *Get_Folder(int _i_Index);
C_SSF_Folder *Get_Folder(char *_pch_Name);
//^-----errors
};
#endif C_SSF_FOLDER_CONTAINER_H
my third class
#ifndef C_SSF_FOLDER_H
#define C_SSF_FOLDER_H
#include <windows.h>
#include <fstream>
#include "C_SSF_Folder_Container.h"
using namespace std;
class C_SSF_Folder {
public:
private:
C_SSF_Folder_Container cl_SSFFC_Folder_Container;
public:
};
#endif
my third class C_SSF_Folder.
I am including "C_SSF_Folder_Container.h"
and declaring a C_SSF_Folder_Container container.
Before declaring the variable it compiles fine. After I declare it
I get syntax errors in my C_SSF_Folder_Container
Severity Code Description Project File Line Suppression State
Error C2061 syntax error: identifier 'C_SSF_Folder' CSSFileSystem\projects\cssfilesystem\cssfilesystem\c_ssf_folder_container.h 16
Error C2061 syntax error: identifier 'C_SSF_Folder' CSSFileSystem \projects\cssfilesystem\cssfilesystem\c_ssf_folder_container.h 19
As I myself look into it I think there is a problem because my C_SSF_Folder is including C_SSF_Folder_Container.
and C_SSF_Folder_Container is including C_SSF_Folder
but the defines should take care of it? Other than that I have no clue what's the problem.
Everything is typed correctly.
You've got a circular #include -- C_SSF_Folder_Container.h #includes C_SSF_Folder.h and C_SSF_Folder.h #includes C_SSF_Folder_Container.h.
This would cause an infinite regress (and a compiler crash) except that you've got the #ifndef/#define guards at the top of your files (as you should); and because of them, instead what you get is that one of those two .h files can't see the other one, and that's why you get those errors.
The only way to fix the problem is to break the circle by deleting one of the two #includes that comprise it. I suggest deleting the #include "C_SSF_Folder.h" from C_SSF_Folder_Container.h and using a forward declaration (e.g. class C_SSF_Folder; instead.
C_SSF_Folder.h and C_SSD_Folder_Container.h are including each other(Circular Dependency).
When the compiler compiles C_SSF_Folder_Container object, it needs to create a C_SSF_Folder object as its field, however, the compiler needs to know the size of C_SSF_Folder object, so it reaches C_SSF_Folder object and tries to construct it. Here is the problem, when the compiler is constructing C_SSF_Folder object, the object has a C_SSF_Folder_Container object as its field, which is a typical chicken and egg question, both files depends on each other in order to compile.
So the correct way to do it is to use a forward declaration to break the circular dependency(including each other).
In your C_SSF_Folder.h, make a forward declaration of C_SSF_Folder_Container.
#include <windows.h>
#include <fstream>
using namespace std;
class C_SSF_Folder_Container;
class C_SSF_Folder {
public:
private:
C_SSF_Folder_Container cl_SSFFC_Folder_Container;
public:
};
#endif
Finally, include C_SSF_Folder_Container.h in your C_SSF_Folder.cpp.
You can also learn more in the following links:
Circular Dependency (Wiki):
https://en.wikipedia.org/wiki/Circular_dependency
Forward Declaration by Scott Langham
What are forward declarations in C++?
This is my first question, so I apologize in advance for any things about stack overflow that I may not be aware of!
The issue I am having is that I am making a simple SDL program, currently it is just supposed to draw a PNG image (Assets/Board.png) to the screen, but I am being faced with many errors to do with the two classes communicating with each other, I think that I have circular inclusion errors. But I have been trying to fix the problem for days and I haven't been able to solve it.
Here are the errors that I am getting:
http://imgur.com/gallery/vq3XLwU/new
(Here is a text version of it, but the formatting is bad sorry)
1>d:\code\c++\games\chess\chess\manager.h(41): error C2079: 'Manager::Tex' uses undefined class 'Render'
1>d:\code\c++\games\chess\chess\render.h(32): error C2146: syntax error : missing ';' before identifier 'manager'
1>d:\code\c++\games\chess\chess\render.h(32): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>d:\code\c++\games\chess\chess\render.h(32): error C2146: syntax error : missing ';' before identifier 'manager'
1>d:\code\c++\games\chess\chess\render.h(32): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
(I have used an image because the formatting of the image is easier to read.)
(Also click on the image in imgur to see the zoomed in version)
You can download the entire code project here (ZIP FILE):
https://www.mediafire.com/?og21315fc1d58sk
But here is the code that I think is causing the issues:
(Manager.h file)
//Include guards.
#pragma once
//Headers.
#include "Render.h"
//Librarys.
#include <SDL_image.h>
#include <string>
#include <SDL.h>
//Namespaces.
using namespace std;
//Enumerator.
enum State { Play, Exit };
class Manager
{
public:
Manager(); //Constructor.
~Manager(); //Destructor.
//Rendering.
SDL_Window* Window;
SDL_Surface* Screen;
SDL_Renderer* Renderer;
//Functions.
void Run();
void Init();
void Close();
void Input();
void Update();
void Error(string);
//Game variables.
State state;
Render Tex;
private:
//Constant values.
const int WINDOW_POS_X = SDL_WINDOWPOS_CENTERED;
const int WINDOW_POS_Y = SDL_WINDOWPOS_CENTERED;
const int INIT_FLAGS = SDL_INIT_VIDEO;
const int SCREEN_HEIGHT = 600;
const int SCREEN_WIDTH = 600;
};
(And here is the Render.h file)
//Include guards.
#pragma once
//Headers.
#include "Manager.h"
//Librarys.
#include <SDL_image.h>
#include <string>
#include <SDL.h>
//Namespaces.
using namespace std;
class Render
{
public:
Render(); //Constructor.
~Render(); //Destructor.
//Functions.
void Draw(int, int); //Draws texture at position.
void Load(string); //Loads texture from path.
void Deallocate(); //Destroy texture.
//Getter functions.
int GetHeight() { return Height; };
int GetWidth() { return Width; };
private:
SDL_Texture* Texture; //Actual image.
Manager manager; //Manager class.
int Height; //Height of image.
int Width; //Wdith of image.
};
So in conclusion, I am having errors related to the class objects, which I believe are being caused by circular inclusion, despite my research I have not been able to fix these issues. I would greatly appreciate any help with this issue.
P.S I know I am not supposed to use the std namespace, instead I must write std::foo, I am aware, so please don't comment about it!
In C++ "ownership" is a very important concept. A class "owns" its members. The problem is you have two objects and you've told the compiler that both "own" the other, which won't do. You have to decide which of them owns the other, and has it as a member (or maybe neither owns the other). At least one class must refer to the other, rather than listing it as a child/member. And the best sort of reference is a pointer.
class Manager;
// this forward declaration tell the compiler the class exists, but
// we don't care about the details yet, so we won't include the header.
// if we try to include it, that header refers to Render, which the compiler
// hasn't seen yet, so the compiler will fail.
class Render
{
public:
Render(Manager* parent_); //Constructor.
...stuff...
Manager* parent;
};
Cpp file:
#include "manager.h"
#include "render.h"
Render::Render(Manager* parent_)
: parent(parent_)
{}
SUGGESTIONS:
1. Eliminate the "Render.h" include:
There doesn't seem to be anything in "Manager.h" that needs anything in "Render.h" - so why include it?
Similarly, 2. Eliminate the "Manager.h" include.
You can simply use a "forward declaration", instead of including the whole class interface (.h file).
These links might help:
C++ circular include
Headers and Includes: Why and How
Okay, I think that I have solved the problem, thanks to a variety of comments. The solution may not be ellegant but it works. Instead of defining the Render Tex variabel inside the Manager header, I declared it inside the Manager.cpp class. Once I had done that I can #include "Render.h" inside the Manager .cpp file. I dont know if that explanation is clear but here is the top of the manager.h file:
//Include guards.
#pragma once
//Librarys.
#include <SDL_image.h>
#include <string>
#include <SDL.h>
And here is the top of the Manager.cpp file:
//Header.
#include "Manager.h"
#include "Render.h"
//Librarys.
#include <iostream>
//Objects.
Render Tex;
I am having much trouble learning to use files for classes in C++. To learn I use Bucky Roberts/The New Boston C++ tutorials, I have tried exactly what he does, but it does not work.
I have the main.cpp and the OtherClass.cpp with the OtherClass.h for header. Every time I try doing OtherClass::OtherClass(){} for the constructor it errors out with "C++ requires a type specifier for all declarations"
Could someone give me an example of how to do C++ class files correctly? Really confused right now.
Thanks!
A simple example of using header files for classes (with the implementation in a separate .cpp file) looks something like this:
Your main.cpp file:
#include "OtherClass.h"
int main()
{
OtherClass otherClass;
//use otherClass here...
}
Next, your OtherClass.h file:
class OtherClass
{
public:
OtherClass();
int someFunction(int parameters);
};
And then finally your OtherClass.cpp file:
#include "OtherClass.h"
OtherClass::OtherClass()
{
//implementation here
}
int OtherClass::someFunction(int parameters)
{
//implemenation here
return 0;
}
The main things to keep in mind:
#include "OtherClass.h" goes in both OtherClass.cpp and main.cpp
make sure you finish constructor and function declarations with ';' not '{}' if you are defining the implementation elsewhere.
make sure you're compiling OtherClass.cpp as well as main.cpp. With MinGW this looks like g++ main.cpp OtherClass.cpp
Your question is a little cryptic to understand, but if I understand correctly you're looking for the `correct' way to create classes with interfaces in the header file. Here is an example of a class that does this:
Scene.h
#pragma once
#include "Window.h"
#include "Entity.h"
class Scene
{
public:
Scene(Window *_window);
~Scene(void);
void render(Entity item);
void render(Entity item, SDL_Rect *clip);
protected:
Window *window;
};
Scene.cpp
#include "Scene.h"
Scene::Scene(Window *_window)
{
window = _window;
}
Scene::~Scene(void)
{
}
void Scene::render(Entity item) {
render(item, NULL);
}
void Scene::render(Entity item, SDL_Rect *clip) {
window->draw( item.getImage(), item.getCoordinates(), clip, item.getAngle() );
}
Notice that the header file includes the headers that it needs to link properly, while the implementation file (.cpp) just includes the header file. The linker should automatically manage all this trouble for you as long as you stick to these semantics.
I hope this helps; if it doesn't, consider rephrasing your question or pasting some code.
I have a trouble with my c++ code. I know there is much advices with error "expected class-name before ‘{’ token" but I still can't find where I have it. Here is my sources:
Postava.h
#include <exception>
#include <string>
using namespace std;
#ifndef __Postava_h__
#define __Postava_h__
#include "Barva.h"
#include "Pozice.h"
//#include "Budova.h"
//#include "HerniEngine.h"
#include "GrafickyObjekt.h"
class Budova;
class HerniEngine;
//class GrafickyObjekt;
class Postava;
struct Barva;
struct Pozice;
class Postava:public GrafickyObjekt{ //<----- Here is the error
private:
std::string m_jmeno;
int m_nosnost;
public:
Postava(std::string jmeno, int nosnost);
Budova* m_Budova;
HerniEngine* m_HerniEngine;
std::string vratJmeno();
int vratNosnost();
void vykresli();
};
#endif
GrafickyObjekt.h
#ifndef __GrafickyObjekt_h__
#define __GrafickyObjekt_h__
#include "HerniEngine.h"
#include "Pozice.h"
#include "Posun.h"
class HerniEngine;
class GrafickyObjekt;
class Scena;
struct Pozice;
struct Posun;
class HerniEngine;
class GrafickyObjekt {
protected:
Pozice m_pozice;
public:
HerniEngine* m_HerniEngine;
// kazdy potomek, tj. graf. obj. ma pozici
GrafickyObjekt(Pozice pozice);
// vsichni potomci ji musi implementovat
virtual void vykresli() = 0;
// tyto metody nejsou (ciste) virtualni, budou normalne zdedeny
// tim mam zaruceno, ze vsichni potomci je maji
void pohni(Posun posun);
void pohni(Pozice pozice);
};
#endif
Sorry for my english and for names of classes and names of variables, it's in czech.
Thanks a lot for every advice.
Same answer as in all similar questions asked before:
You created a circular include sequence
It is not obvious from what you posted so far (since you haven't posted all headers). But it is a safe bet that your other header files taken together must produce a circular include "path". More precisely, your GrafickyObjekt.h somehow indirectly includes Postava.h (through other header files that you haven't posted).
The include guards you used in your header files will "break" that cycle in some unpredictable or (better word) unforeseen way. In your case the include guards caused Postava.h to get physically included first, which is why it knows nothing about GrafickyObjekt even though it seems to explicitly include GrafickyObjekt.h. Hence the error.
Circular includes make no sense and achieve nothing. You have to stratify your headers by levels - from low level to high level - and make sure that higher-level headers include lower-level headers, but never the other way around.
Once you achieve that sort of order, you can proceed to resolving circular data dependencies by introducing forward class declarations. I see that you already tried to do that and ended up with a total catastrophic mess, where you basically forward-declare all classes in all headers. Get rid of that mess and start over, by fixing the include stratification first.
It seems that some of your previous includes are faulty.
#include "HerniEngine.h"
#include "Pozice.h"
#include "Posun.h"