cyntanic
cyntanic

Reputation: 13

C++ SDL2 window not opening

i coded this.

#include <iostream>
#include "SDL.h"

int main(int argc , char** args)
{
    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_Window* win = SDL_CreateWindow("my window", 100, 100, 640, 480, SDL_WINDOW_SHOWN);

if (!win) 
{
    std :: cout << "Failed to create a window! Error: " << SDL_GetError() << "\n";

}


SDL_Surface* winSurface = SDL_GetWindowSurface(win);



SDL_UpdateWindowSurface(win);

SDL_FillRect(winSurface, NULL, SDL_MapRGB(winSurface->format, 255, 90, 120));

SDL_DestroyWindow(win);
win = NULL;
winSurface = NULL;

return 0;




}

when i compile it, it opens the window, and it immediately closes. But the console doesn't. Here is a screenshot of my console(maybe it could help solving the problem?)

screenshot

Would there be any solution to get the Window to not close?

Upvotes: 1

Views: 496

Answers (1)

genpfault
genpfault

Reputation: 52084

Would there be any solution to get the Window to not close?

Start up an event-handling loop and handle some events:

// g++ main.cpp `pkg-config --cflags --libs sdl2`
#include <SDL.h>
#include <iostream>

int main( int argc, char** argv )
{
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Window* win = SDL_CreateWindow("my window", 100, 100, 640, 480, SDL_WINDOW_SHOWN);

    if (!win)
    {
        std :: cout << "Failed to create a window! Error: " << SDL_GetError() << "\n";
    }

    SDL_Surface* winSurface = SDL_GetWindowSurface(win);

    bool running = true;
    while( running )
    {
        SDL_Event ev;
        while( SDL_PollEvent( &ev ) )
        {
            if( ( SDL_QUIT == ev.type ) ||
                ( SDL_KEYDOWN == ev.type && SDL_SCANCODE_ESCAPE == ev.key.keysym.scancode ) )
            {
                running = false;
                break;
            }
        }

        SDL_FillRect(winSurface, NULL, SDL_MapRGB(winSurface->format, 255, 90, 120));
        SDL_UpdateWindowSurface(win);
    }

    SDL_DestroyWindow(win);
    SDL_Quit();
    return 0;
}

Upvotes: 2

Related Questions