Search code examples
c++windowsdl

SDL Window won't pop up


My window won't pop up.

Console appears, and without opening window just says that "Application ended"

Here is my code:

#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_image.h>
#include <windows.h>

using namespace std;

SDL_Window * okno;
SDL_Surface * ekran;
SDL_Event zdarzenie;

int frame = 0;

int main(int argc, char*args[])
{
    SDL_Init(SDL_INIT_EVERYTHING);
    return 0;

    okno = SDL_CreateWindow("SDL_TEST", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, NULL);

    ekran = SDL_GetWindowSurface(okno);

}

Solution

  • return 0; is your bug. After the return the program ends because main() ends. No lines in main are executed after the return. You certainly did not want to end before you called SDL_CreateWindow.

    Can a function continue after a return statement?

    Change the code to

    #include <iostream>
    #include <SDL2/SDL.h>
    #include <SDL2/SDL_ttf.h>
    #include <SDL2/SDL_mixer.h>
    #include <SDL2/SDL_image.h>
    #include <windows.h>
    
    using namespace std;
    
    SDL_Window * okno;
    SDL_Surface * ekran;
    SDL_Event zdarzenie;
    
    int frame = 0;
    
    int main(int argc, char*args[])
    {
        SDL_Init(SDL_INIT_EVERYTHING);
    
        okno = SDL_CreateWindow("SDL_TEST", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, NULL);
    
        ekran = SDL_GetWindowSurface(okno);
    
    }
    

    In c++ return 0; can be omitted from main.

    Can I omit return from main in C?

    Also I would expect this code to issue a warning (about unreachable code) on many compilers. If it did not warn you may need to turn up the warning level of your compiler. If it did warn you need to pay more attention to the warnings..

    You may also want to remove the global variables and instead make your variables local to main. Global variables are usually considered a bad practice.

    Are global variables bad?

    Also SDL_Init() can fail. You may want to check its return value and quit on failure logging the error.

    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
        return 1;
    }
    

    https://wiki.libsdl.org/SDL_Init