Search code examples
c++sdlfreeze

SDL: Window freezes


I wanted to start working on SDL. I got a sample code to see if it worked fine. When compiling I get no errors, but when I run it the window shows up but the program freezes until the delay time is over. I'm new to this so I would really appreciate some help.

int main(int argc, char* argv[]) {

SDL_Init(SDL_INIT_EVERYTHING);

SDL_Window *window = 0;

window = SDL_CreateWindow("Hello World!",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        640, 480,
        SDL_WINDOW_SHOWN);

SDL_Delay(10000);

SDL_DestroyWindow(window);
SDL_Quit();

return 0;

}


Solution

  • As mentioned by @HolyBlackCat, you need an event loop : https://wiki.libsdl.org/SDL_PollEvent

    It should look something like this :

    while (true) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            /* handle your event here */
        }
        /* do some other stuff here -- draw your app, etc. */
    }
    

    Edit
    You will need to replace your delay with the event loop. Instead, you can close the application on an event. The least you can/should do, is handle the SDL_QUIT event, which is sent when the user try to close the window:

    while (!quit) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            /* handle your event here */
    
           //User requests quit
            if( event.type == SDL_QUIT )
                quit = true;
        }
        /* do some other stuff here -- draw your app, etc. */
    }