DEV Community

dwarfŧ
dwarfŧ

Posted on

create a window in SDL2 for any OS

step 1
first we need to import SDL2 into our main.c project. However there are different library's for every OS so we can allow the computer to choose the needed one by doing this:

#include <stdio.h> /* printf and fprintf */
#include <stdbool.h>
#ifdef _WIN32
#include <SDL/SDL.h> /* Windows-specific SDL2 library */
#else
#include <SDL2/SDL.h> /* macOS- and GNU/Linux-specific */
#endif
Enter fullscreen mode Exit fullscreen mode

step 2
to make the window with a title and window size we can do:

int main() {
    SDL_Init(SDL_INIT_VIDEO);

    SDL_Window* w = SDL_CreateWindow(
        /* If you flip this, SDL_SetWindowTitle() below starts working */
        #if 1
        "hello window!",
        #else
        "hello window!",
        #endif
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
        400, 400, 0); // window size

    /* If you call this, the below stops working */
    //SDL_SetWindowTitle(w, "Another title without UTF-8");

    /* This works only if the previously set title had an em-dash as well */
    SDL_SetWindowTitle(w, "hello window!"); //title

    SDL_Event event;
    while(SDL_WaitEvent(&event))
        if(event.type == SDL_QUIT) break;

    SDL_DestroyWindow(w);
    SDL_Quit();
}
Enter fullscreen mode Exit fullscreen mode

this sets the window size and title.

step3
to compile our main.c file with g++ we can do:

g++ -o main main.c -lSDL2
Enter fullscreen mode Exit fullscreen mode

and run it with:

./main
Enter fullscreen mode Exit fullscreen mode

step4
enjoy and have a good day

Oldest comments (0)