When I compile and run a simple application in C which uses the SDL library (version 2) the window seems to open twice; first I see a window which opens and closes really rapidly and then the window comes up and stays (for two seconds). Any ideas what may be causing this?
Here is the test program:
#include <SDL2/SDL.h>
#include <stdio.h>
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
int main(int argc, char* args[]) {
SDL_Window* window = NULL;
SDL_Surface* screenSurface = NULL;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "could not initialize sdl2: %sn", SDL_GetError());
return 1;
}
window = SDL_CreateWindow(
"hello_sdl2",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH, SCREEN_HEIGHT,
SDL_WINDOW_SHOWN
);
if (window == NULL) {
fprintf(stderr, "could not create window: %sn", SDL_GetError());
return 1;
}
screenSurface = SDL_GetWindowSurface(window);
SDL_FillRect(screenSurface, NULL, SDL_MapRGB(screenSurface->format, 0xFF, 0xFF, 0xFF));
SDL_UpdateWindowSurface(window);
SDL_Delay(2000);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
I compile the program with
gcc -o hello_sdl2 hello_sdl2.c -lSDL2
and the version is
$ gcc --version
gcc (Debian 12.2.0-14) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ sdl2-config --version
2.26.5
Edit 2024-08-27:
$ cat /etc/debian_version
12.6
$ wmctrl -m
Name: Blackbox
Class: N/A
PID: N/A
Window manager's "showing the desktop" mode: N/A
2
Answers
As pointed out by Ted Lyngmo in the comments the solution is to use the flag SDL_WINDOW_HIDDEN in the call to SDL_CreateWindow and then call SDL_ShowWindow after the call to SDL_GetWindowSurface:
Note: If SDL_ShowWindow is called before SDL_GetWindowSurface the "flickering" issue remains.
try adding a check in case the program runs twice