Hi I bought the book SDL Game Development from Amazon because I want to learn how to write games with SDL2, I got through the first examples but when it comes to splitting up in to separate c++ files I find errors a bit harder to spot. Can anyone tell me why my first attempt at a game engine skeleton out of the book segfaults at> Thread 1 “a.out” received signal SIGSEGV, Segmentation fault.
0x0000555555554cfb in Game::init(char const*, int, int, int, int, int) () according to gdb
I would really appreciate any help from a more experienced programmer to get this boiler plate code up and running because I don’t really have anywhere else to go or much info about how to fix the segfault except the function which is causing it which can’t really be changed
Thanks.
main.cpp
#include <SDL2/SDL.h>
#include “Game.h”
#include “Game.cpp”
int main(int argc, char * args[])
{
Game * g_game = 0;
g_game->init(“Chapter 1”, 100,100,640,480,SDL_WINDOW_RESIZABLE);
while(g_game->running())
{
g_game->handleEvents();
g_game->update();
g_game->renderer();
}
g_game->clean();
return 0;
}
Game.cpp
#include “Game.h”
#include
bool Game::init(const char* title, int xpos, int ypos, int width,
int height, int flags)
{
// attempt to initialize SDL
if(SDL_Init(SDL_INIT_EVERYTHING) == 0)
{
std::cout<<“SDL Init Success\n”;
// init the window
m_pWindow = SDL_CreateWindow(title, xpos, ypos, width, height, flags);
if(m_pWindow !=0)
{
std::cout<<"Window Creation Success\n";
m_pRenderer = SDL_CreateRenderer(m_pWindow, -1,0);
if(m_pRenderer !=0) // render init success
{
std::cout<<"Renderer Creation Success\n";
SDL_SetRenderDrawColor(m_pRenderer, 255,255,255,255);
}
else
{
std::cout<<"Renderer Init Fail\n";
return false; // renderer init fail
}
}
else
{
std::cout<<"Window Init Fail\n";
return false; //window init fail
}
}
else
{
std::cout<<“SDL Init Fail\n”;
return false; // SDL init fail
}
std::cout<<“Init success\n”;
m_bRunning = true; // everything inited successfully
// start the main loop
return true;
}
void Game::renderer()
{
SDL_RenderClear(m_pRenderer); // clears the renderer
// to the draw colour
SDL_RenderPresent(m_pRenderer); // draw to the screen
}
void Game::update()
{
}
void Game::clean()
{
std::cout<<“Cleaning window\n”;
SDL_DestroyWindow(m_pWindow);
SDL_DestroyRenderer(m_pRenderer);
SDL_Quit();
}
void Game::handleEvents()
{
SDL_Event event;
if(SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
m_bRunning = false;
break;
}
}
}
Game.h
#ifndef Game
#define Game
class Game
{
public:
Game() {}
~Game() {}
// simply set the running variable to true
bool init(const char* title, int xpos, int ypos, int width,
int height, int flags);
void renderer();
void update();
void handleEvents();
void clean();
// a function to access the private running variable
bool running() {return m_bRunning;}
private:
SDL_Window * m_pWindow;
SDL_Renderer * m_pRenderer;
bool m_bRunning;
};
#endif /* defined(Game_h) */
compiled with g++ main.cpp -lSDL2