c++sdlsdl-3

SDL_Init() fails without returning an error?


When I try to execute this SDL3 program:

// g++ -Wall -Ofast main.cpp -Iinclude -Iinclude/SDL3 -Linclude/SDL3 -lSDL3 -o build/program
#define SDL_MAIN_HANDLED
#include <iostream>
#include <SDL3/SDL_main.h>
#include <SDL3/SDL.h>

int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        SDL_Log("SDL_Init failed: %s", SDL_GetError());
        return -1;
    }

    return 0;
}

... I get the following error:

SDL_Init failed:

(Note: SDL_GetError() doesn't return anything).

I'm using Windows 10 Pro.


Solution

  • There was a change in the API between SDL2 and SDL3.

    In SDL2, SDL_Init returns an int which is:

    0 on success or a negative error code on failure;

    But in SDL3, SDL_Init returns a bool which is:

    true on success or false on failure;

    I.e. 0 means success in SDL2 but failure in SDL3.

    Since you are using SDL3 your call to SDL_Init (which returned a value != 0), actually succeeded.

    You should change the calling code to:

    //--v---------------------------
    if (!SDL_Init(SDL_INIT_VIDEO)) {
         SDL_Log("SDL_Init failed: %s", SDL_GetError());
         return -1;
    }
    

    (or compare explicitly against false if you prefer that style).