C++ SDL header file errors - c++

I'm following a tutorial and it said at one point it should compile, but it errored.
To find out why I just used their code instead of mine and have just pasted all theirs in, however, this is picking up errors. It's in a header file, I've placed the errors below the code
#ifndef _CApp_H_
#define _CApp_H_
#include <SDL.h>
class CApp {
private:
bool Running;
public:
CApp();
int OnExecute();
public:
bool OnInit();
void OnEvent(SDL_Event* Event);
void OnLoop();
void OnRender();
void OnCleanup();
};
#endif
Errors:
Syntax error before CAPP, on line 6.
Syntax error before the first {, on line 6.
Syntax error before : on line 14.
Line 25 before }
All files are declared. I have another error, too, here:
#include "CApp.h"
void CApp::OnCleanup() {
}
Before :. it doesn't give more description than that apart from it's on line 3.

Is the SDL.h file in your include path? Nothing in the example jumps out at me as wrong.

This isn't really a proper answer to your question, but...
I would highly recommend switching to SFML instead of SDL. It's essentially a modernized, object-oriented SFML written in C++. It has many advantages over SDL (such as fully hardware-accelerated 2D drawing). Check it out if you'd like.

It's probably located in a path. Try putting # include "SDL\SDL.h".

Related

C++ - Many parse Issues in NSObjCRuntime and NSZone

I'm using the AppGameKit 2 C++ libraries with Xcode.
I'm using a template project that's given for development on Mac OSX and my code is identical to the default template save for changing a initWithCString to initWithUTF8String, but it compiled after that anyway, so it's not a problem.
The problem started when I tried to rename one of the classes that comes with the template, called template.h/.cpp. The option to rename in the refactor menu was greyed out, so I duplicated the class and changed all of the #includes to point to the new class, then removed the old one from the project.
When I hit run, I got about 20 errors all saying stuff like Unknown type name 'NSString' and Unknown type name 'Protocol'.
I looked around and found answers like this one: ios - Parse Issues in NSObjCRuntime, NSZone, and NSObject but it didn't solve the issue, because according to those, my code should work.
The includes of the main class (Core.mm) is here:
// includes
#import <Cocoa/Cocoa.h>
#include "agk.h"
#include "template.h"
The code in template.h is here:
#ifndef _H_APP
#define _H_APP
// Include AGK libraries
#include "agk.h"
// used in Core.mm to set the window properties
#define DEVICE_WIDTH 1280
#define DEVICE_HEIGHT 720
#define WINDOW_TITLE "Title"
#define FULLSCREEN 0
// Global values for the app
class app
{
public:
// global game vars
public:
// constructor
app() {}
~app() {}
void Begin( void );
void Loop( void );
void End( void );
};
extern app App;
#endif
The code in template.cpp is here:
// Includes
#include "template.h"
// Namespace
using namespace AGK;
app App;
void app::Begin (void){
agk::SetVirtualResolution (1280, 720);
agk::SetClearColor(0,0,0); // light blue
agk::SetSyncRate(60,0);
agk::SetScissor(0,0,0,0);
}
void app::Loop (void){
agk::Print( agk::ScreenFPS() );
agk::Sync();
}
void app::End (void){}
I can't make any sense of this because it shouldn't make sense.
Well, I found the problem. In the template project, the template.cpp file was marked as an Objective-C++ source file, but it obviously wasn't being reimported as one. Changing the file type fixed the problem.
Xcode 11.7
( in 2020 )
change the type, to do it more intuitively
This is cause you imports C or C++ file in your project.For this you add all your header file that imported in .pch file or any common file should declare like this:
#ifdef __OBJ C__
//Import header file
#endif

File Causing Thousands of Errors (C++) [closed]

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.

Compiling C++ code on Linux. Need to use intel/icpc compiler. Error: "multiple definitions" related to inerited class

I am trying to compile a large C++ code (there are a few C files too) on a Linux cluster, having run it for some time on a Mac compiled with g++. On the cluster, I have to use either gcc/4.7.2 or intel/icpc (there is other software on the cluster that only works with those two compilers). I'm a newbie in dealing with compiling/linking problems, so no advice/tips is too simple.
I posted a question here a couple of days ago about a problem with using gcc/4.7.2. I haven't been able to resolve the problem, so now I'm trying icpc. Things have gone surprisingly well, but there is one problem I can't get past.
The problem is that I am getting errors related to "multiple definitions." These are associated with what seems to be a virtual function in a class that is inherited. I didn't write this code. There is a base class (Solver3), a derived class (Solver2), and another derived class (Solver1). The classes solve matrix equations. I can't tell which function is the problem because the error output is quite cryptic (see below; I have no function called "_fileno" and I can't find any generic definition of this term online). But the problem function is probably SolveWithSolver2 because it is the only function in the Solver1 class. I have no clue what could be wrong with it.
This is a bit over my head in terms of C++ knowledge and it is likely I'm making some beginner's mistake. For the past couple of days, I have used Google to search old forum posts. I have tried renaming what seems to be the problem function, I have tried inlining it. I get the same error. The code is very large and only a small part of it was written by me, so I can't post much of it. I will post what seems relevant and can add things if that would be helpful.
Here are the kinds of the errors I'm getting, starting from the first one (I have not posted all of the output):
/code/libraries/libsolver.a(Solver1.o): In
function _fileno(_IO_FILE*)': Solver1.cpp:(.text+0x0): multiple
definition of_fileno(_IO_FILE*)' main.o:main.cpp:(.text+0x1bc0):
first defined here
/code/libraries/libsolver.a(Solver2.o): In
function _fileno(_IO_FILE*)': Solver2.cpp:(.text+0x0): multiple
definition of_fileno(_IO_FILE*)' main.o:main.cpp:(.text+0x1bc0):
first defined here
/code/libraries/libsolver.a(Solver3.o):
In function _fileno(_IO_FILE*)':
Solver3.cpp:(.text+0x0): multiple definition of_fileno(_IO_FILE*)'
main.o:main.cpp:(.text+0x1bc0): first defined here
... And so on
Here is the Solver1 header code:
#ifndef SOLVER1
#define SOLVER1
#include "Solver2.h"
#include "ErrorHandler.h"
#ifdef SOLVER2
namespace code {
class Solver1 : public Solver2 {
public:
Solver1( );
//protected:
virtual void SolveWithSolver2( Matrix& A,
std::vector<double>& b,
std::vector<double>& x,
double tolerance );
private:
double pivot;
};
}
#endif
#endif
Here is the Solver2 header code:
#ifndef SOLVER2_H
#define SOLVER2_H
#include "Solver3.h"
#include "helper.h"
#ifdef SOLVER2
namespace code {
class Solver2: public Solver3 {
public:
Solver2 ();
//protected:
virtual void SolveWithSolver2(Matrix& A,
std::vector<double>& b,
std::vector<double>& x,
double tolerance) = 0;
private:
virtual void SolveEquation(Matrix& A,
std::vector<double>& b,
std::vector<double>& x,
stl_index unknowns);
double Residual(const Matrix& A,
const std::vector<double>& b,
std::vector< double >& x);
double Calculate(const SparseMatrix& A,
const std::vector<double >& b,
const std::vector< double >& x);
double residual;
};
}
#endif
#endif
Reply to Jakob:
Output of:
"grep _fileno" /usr/include/* -R
/usr/include/bits/dirent.h:#define d_fileno d_ino /* Backwards
compatibility. */ grep: warning:
/usr/include/c++/4.3/x86_64-suse-linux/32: recursive directory loop
/usr/include/dirent.h:#if (defined __USE_BSD || defined __USE_MISC) &&
!defined d_fileno /usr/include/dirent.h:# define d_ino d_fileno /*
Backward compatibility. */ /usr/include/lcms.h:# define fileno
_fileno /usr/include/libdwarf/libdwarf.h: Dwarf_Unsigned * /*ret_fileno*/, /usr/include/libio.h:#define _IO_DELETE_DONT_CLOSE
0x40 /* Don't call close(_fileno) on cleanup. */ /usr/include/libio.h:
int _fileno; /usr/include/linux/coda.h: u_int32_t d_fileno; /*
file number of entry */ /usr/include/linux/mtio.h: __kernel_daddr_t
mt_fileno; /* number of current file on tape */
/usr/include/sys/mtio.h: __daddr_t mt_fileno; /* Number of current
file on tape. */ /usr/include/X11/Xw32defs.h:#define fileno _fileno
Edit:
Using Jakob's suggestion about compiler flags (adding -Wl and -z) to my OPTIONS, my error output became much more clear; I got file names, line numbers, and particular errors.
I have now dealt with the problem, in the sense that I can compile that library. But to be honest, I don't really know why the compiler complained to begin with or why my solution worked. The problem involved preprocessor directives, which I confess I know little about. If anyone cares to speculate on what the issue was, it would be interesting to know. I have never run into needing ";" in preprocessor directives before.
This is what "fixed" things (sorry about the bold, large text; can't seem to turn that off):
define SOLVER_C_CONVERSION;
void __cdecl;
endif
This is what it looked like when it was a problem:
define SOLVER_C_CONVERSION void __cdecl
endif
So now that I've fixed that problem, I have one more library to deal with. It is throwing up all kinds of errors that g++ previously ignored. I may bother you all once more later on today if I can't solve them. I'm pretty sure the problem is with my makefile.
To solve the problem with the multiple definitions, the first step would probably be
tracking down the include dependencies,
using the '-M' or the '-H' compiler flag,
e.g. :
gcc -H {use correct include flags here: -I$( include path) } -c Solver1.cpp
This will show you a dependency tree (read top-down )
Then you could figure out, which of the files defines the _fileno symbol.
(e.g by using the grep command)
and finally you could try to understand, why _fileno is defined multiple times.
If you want a nicer dependency output, you could in general try to generate the include dependencies with doxygen.
Alternatively as a workaround you could use following link flags which will prevent the compilation process from failing in case of multiple definitions:
-Wl,-z,multiple

What's causing these linker errors? (Visual C++ LNK2005)

I'm a novice programmer, still in the midst of trying to learn C++ and OOP design basics. The project that I've been working on to teach myself is a C++ game that has multiple classes, files, states, etc. However, I keep running into snags with file organization that range from simply struggling with where to create objects to compile-breaking linker errors.
Here's an example of some of the errors that I've been getting:
1>SMGA.obj : error LNK2005: "class Engine smgaEngine" (?smgaEngine##3VEngine##A) already defined in Engine.obj
1>SplashScreenState.obj : error LNK2005: "class Engine smgaEngine" (?smgaEngine##3VEngine##A) already defined in Engine.obj
1>StateManager.obj : error LNK2005: "class StateManager gameStateManager" (?gameStateManager##3VStateManager##A) already defined in Engine.obj
1>MSVCRTD.lib(cinitexe.obj) : warning LNK4098: defaultlib 'msvcrt.lib' conflicts with use of other libs; use /NODEFAULTLIB:library
I've looked around online and I've seen a lot of ~similar~ problems that involve bad include guards or the inclusion of .cpp files instead of .h files. But I haven't done that in my code, so I'm at a loss.
Now, I'm guessing that the error is telling me that I'm trying to create the smgaEngine object of the Engine class (and the gameStateManager object of the StateManager class) twice, but I'm not sure why...
The thing that stands out about these two objects (smgaEngine and gameStateManager) is that I declared them in their corresponding class' .h files immediately after the class declaration. Could this be the issue? - They're still within the include guards, and I wasn't too sure about where else to put them in my code... Would this sloppy coding be the cause of linker errors?
Here's one of the suspect classes...
#ifndef ENGINE_H
#define ENGINE_H
#include <SDL.h>
#include "Timer.h"
class Engine
{
private:
static const int screenWidth = 480;
static const int screenHeight = 270;
static const int screenBPP = 24;
bool running;
SDL_Surface *mainScreen;
SDL_Event eventHolder;
Timer fpsTimer;
public:
Engine();
~Engine();
void init();
void handleEvents();
void handleLogic();
void handleRender();
void cleanUp();
SDL_Event *getEvent();
SDL_Surface *getMainScreen();
bool isRunning();
void setRunning(bool tempRunning);
} smgaEngine;
#endif
And here's the other one:
#ifndef STATEMANAGER_H
#define STATEMANAGER_H
#include "SplashScreenState.h"
#include <vector>
class GameState;
class StateManager
{
private:
std::vector<GameState*> stateStack;
SplashScreenState *splashState;
public:
StateManager();
~StateManager();
void init();
void changeState( GameState *tempNextState );
void addState( GameState *tempNextState );
void removeState();
//returns the back() element of the stateStack vector..
GameState* getTopState();
void handleEvents();
void handleLogic();
void handleRender();
} gameStateManager;
#endif
I've been trying my best to learn C++ and OOP, but I've really been struggling. It seems that every time I attempt to make clean code with encapsulated classes, I end up with a confusing mess. I'm trying to prevent a high degree of class coupling, but I often end up with either linker errors or a lack of ability to communicate between classes... Is it creation of class instance objects within the header files that is causing these errors or is it something else? And if that is the cause of my linker errors, then where should I be creating these objects?
You have defined two global variables, smgaEngine and gameStateManager in your header files, and you have included those header files in two (or more) source files. So you get multiple definition errors. Include guards don't stop header files being included twice in different source files (how could they?) they stop header files being included twice in the same source file.
You're quite close to the correct answer (at least you have a good understanding of the problem). The right way is this
// header file Engine.h
class Engine
{
};
extern Engine smgaEngine;
// in one source file (say Engine.cpp)
Engine smgaEngine;
What you have now is a declaration in the header file (extern makes it a declaration), but a definition in the source file. You can have as many declarations as you like (as long as they are consistent) but you must have only one definition. So for global variables put declarations in the header file and put a definition in one of the source files.

Compiler Hiccup in C++ and with .o Files

I've been trying to compile a multi-file project, but every time I try to use a void in player.cpp, I keep getting this error message, which appears that the player.o that is created during compilation has the same definition of void player_action(...). When I tried to use a void in the other files, the same problem occurs, with their corresponding .o file. However, if I use structs in any of the files, no problems occurs, and no "multiple definition" error occurs. In the lines below is the error message the compiler is giving me.
obj\Debug\player.o: In function `Z13player_actioniii':
D:/Projects/Blackmail Mailman/player.cpp:13: multiple definition of `player_action(int, int, int)'
obj\Debug\main.o:D:/Projects/Blackmail Mailman/player.cpp:13: first defined here
This is the code from player.cpp I used:
#include "include_files.cpp"
struct player_struct
{
int x;
int y;
int previous_x;
int previous_y;
int mode;
};
void player_action(int x, int y, int mode)
{
SDL_Event event;
if (SDL_PollEvent(&event))
{
if (event.type == SDL_KEYDOWN)
{
switch(event.key.keysym.sym)
{
case SDLK_RIGHT:;
};
};
};
};
What could be wrong and how can I fix it? I'm using Codeblocks with Mingw and Windows XP. I already checked the other files and there aren't any extra definitions of void player_action().
You never #include .cpp files, rather the .h files only.
If you need to access void player_action() from several parts of your program you should make a header file myapi.h which contains the following:
//myapi.h
#ifndef MYAPI_HEADER
#define MYAPI_HEADER
void player_action(int x, int y, int mode);
/* more function declarations */
#endif
The file which defines the function will be like this:
//player.cpp
#include "myapi.h"
void player_action(int x, int y, int mode)
{
/*...*/
}
and the file which uses it will be like this:
//main.cpp
#include "myapi.h"
void GameCycle()
{
/*...*/
player_action(0,0,0);
/*...*/
}
Never include objects definitions with #include, unless you know what you are doing. And even if you do know, you should think twice before doing so. Always use include guards (#ifndef ... #define .. #endif) - this will prevent multiple inclusion of your header.
These are the basic recommendations. I have seen a good explanation of such stuff in B. Stroustrup's 'The C++ programming language'