Question

I'm currently working with SDL2 and GLFW3 to create some OpenGL game. Initializing and using GLFW3 is no problem; I'm using GLFW3 for creating the OpenGL context, window, key input etc. and SDL2 for loading images to SDLSurfaces and then converting them to OpenGL textures, but, unlike GLFW3, SDL2 fails to initialize. My initialization code looks like this:

if (!SDL_Init(SDL_INIT_EVERYTHING)) return -1;

It always returns -1 and quits the main function. Does anyone know why this could happen?

Was it helpful?

Solution

The problem

The problem is not with SDL. SDL actually initializes completely fine. The problem is how you check if the initialization succeeded. Take a look at the documentation for SDL_Init()

Returns 0 on success or a negative error code on failure; call SDL_GetError() for more information.

In your code code

if (!SDL_Init(SDL_INIT_EVERYTHING)) return -1;

In the if, the SDL_Init(SDL_INIT_EVERYTHING) part will return 0, which evaluates to false but it still means that SDL was successfully initialized. The ! in front, means the entire if will evaluate to true, and -1 will be returned.

Solution

A better soltion is to check if it's equal to 0 and if it does fail, used SDL_GetError() to print the error.

if ( SDL_Init(SDL_INIT_EVERYTHING) != 0 )
{
    std::cout << "Error : " << SDL_GetError() << std::endl;
    return -1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top