Last active
March 14, 2025 02:31
-
-
Save fschr/92958222e35a823e738bb181fe045274 to your computer and use it in GitHub Desktop.
SDL2 Hello World | SDL2 Getting Started | SDL | OpenGL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SDL2 Hello, World! | |
// This should display a white screen for 2 seconds | |
// compile with: clang++ main.cpp -o hello_sdl2 -lSDL2 | |
// run with: ./hello_sdl2 | |
#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: %s\n", 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: %s\n", 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 only get and the program is not executable
Fatal Error: Out of memory - aborting
i had it running, but just a note for windows users:
https://stackoverflow.com/questions/5259714/undefined-reference-to-winmain16
Fixing the above, just use something like gcc hello.c -o hello -I./include -L./lib -lSDL2
(or whatever)
I have since provided a much more extensive PoC for using SDL2, here.
i managed to run it by running the following commands
g++ c.cpp -o c -lSDL2main -lSDL2&& ./c
anyone need help contact me [email protected]
Just FYI for MacOS users. This will not open a window because the delay pauses the process before the window opens. Replace the delay with this:
SDL_Event e;
bool quit = false;
while (!quit){
while (SDL_PollEvent(&e)){
if (e.type == SDL_QUIT){
quit = true;
}
if (e.type == SDL_KEYDOWN){
quit = true;
}
if (e.type == SDL_MOUSEBUTTONDOWN){
quit = true;
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@eabase do you use Linux or Windows?
if in linux just type:
if in windows you need to download from https://libsdl.org, and edit your Makefile to include libSDL (it's a long way)