SDL is Simple DirectMedia Layer.It is a cross-platform development library designed to provide low level access to audio, keyboard, mouse, joystick, and graphics hardware via OpenGL and Direct3D.It can be used to make animations and video games.
- It basically provides a set of APIs to interact with various devices like graphics hardware, audio, keyboard, mouse, etc.
- It is written in C programming language and works with C++ and various other languages like c# and python.
Installation on Linux ( For OS which uses the apt package manager eg : Ubuntu ):
- Run command sudo apt-get update on your terminal.
- Run command sudo apt-get install clang on your terminal.
- Run command sudo apt-get install libsdl2-2.0-0 libsdl2-dbg libsdl2-dev libsdl2-image-2.0-0 libsdl2-image-dbg libsdl2-image-dev on your terminal.
-
we need to make a Makefile.So open a text editor of your choice and start writing the code below.
# A simple Makefile for compiling small SDL projects # set the compiler CC := clang # set the compiler flags CFLAGS := `sdl2-config --libs --cflags` -ggdb3 -O0 --std=c99 -Wall -lSDL2_image -lm # add header files here HDRS := # add source files here SRCS := #file-name.c # generate names of object files OBJS := $(SRCS:.c=.o) # name of executable EXEC := #name your executable file # default recipe all: $(EXEC) showfont: showfont.c Makefile $(CC) -o $@ $@.c $(CFLAGS) $(LIBS) glfont: glfont.c Makefile $(CC) -o $@ $@.c $(CFLAGS) $(LIBS) # recipe for building the final executable $(EXEC): $(OBJS) $(HDRS) Makefile $(CC) -o $@ $(OBJS) $(CFLAGS) # recipe for building object files #$(OBJS): $(@:.o=.c) $(HDRS) Makefile # $(CC) -o $@ $(@:.o=.c) -c $(CFLAGS) # recipe to clean the workspace clean: rm -f $(EXEC) $(OBJS) .PHONY: all clean
Header Files:
// for initializing and sutdown functions #include <SDL2/SDL.h> // for rendering images and graphics on screen #include <SDL2/SDL_image.h> // for using SDL_Delay() functions #include <SDL2/SDL_timer.h> |
Initialization:
#include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_timer.h> int main() { // retutns zero on success else non-zero if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { printf("error initializing SDL: %s\n", SDL_GetError()); } SDL_Window* win = SDL_CreateWindow("GAME", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1000, 1000, 0); while (1) ; return 0; } |
That will create a empty window on your screen.
Output:

We will write a simple program to explain rendering and I/O handling:
#include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_timer.h> int main() { // retutns zero on success else non-zero if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { printf("error initializing SDL: %s\n", SDL_GetError()); } SDL_Window* win = SDL_CreateWindow("GAME", // creates a window SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1000, 1000, 0); // triggers the program that controls // your graphics hardware and sets flags Uint32 render_flags = SDL_RENDERER_ACCELERATED; // creates a renderer to render our images SDL_Renderer* rend = SDL_CreateRenderer(win, -1, render_flags); // creates a surface to load an image into the main memory SDL_Surface* surface; // please provide a path for your image surface = IMG_Load("path"); // loads image to our graphics hardware memory. SDL_Texture* tex = SDL_CreateTextureFromSurface(rend, surface); // clears main-memory SDL_FreeSurface(surface); // let us control our image position // so that we can move it with our keyboard. SDL_Rect dest; // connects our texture with dest to control position SDL_QueryTexture(tex, NULL, NULL, &dest.w;, &dest.h;); // adjust height and width of our image box. dest.w /= 6; dest.h /= 6; // sets initial x-position of object dest.x = (1000 - dest.w) / 2; // sets initial y-position of object dest.y = (1000 - dest.h) / 2; // controls annimation loop int close = 0; // speed of box int speed = 300; // annimation loop while (!close) { SDL_Event event; // Events mangement while (SDL_PollEvent(&event;)) { switch (event.type) { case SDL_QUIT: // handling of close button close = 1; break; case SDL_KEYDOWN: // keyboard API for key pressed switch (event.key.keysym.scancode) { case SDL_SCANCODE_W: case SDL_SCANCODE_UP: dest.y -= speed / 30; break; case SDL_SCANCODE_A: case SDL_SCANCODE_LEFT: dest.x -= speed / 30; break; case SDL_SCANCODE_S: case SDL_SCANCODE_DOWN: dest.y += speed / 30; break; case SDL_SCANCODE_D: case SDL_SCANCODE_RIGHT: dest.x += speed / 30; break; } } } // right boundary if (dest.x + dest.w > 1000) dest.x = 1000 - dest.w; // left boundary if (dest.x < 0) dest.x = 0; // bottom boundary if (dest.y + dest.h > 1000) dest.y = 1000 - dest.h; // upper boundary if (dest.y < 0) dest.y = 0; // clears the screen SDL_RenderClear(rend); SDL_RenderCopy(rend, tex, NULL, &dest;); // triggers the double buffers // for multiple rendering SDL_RenderPresent(rend); // calculates to 60 fps SDL_Delay(1000 / 60); } // destroy texture SDL_DestroyTexture(tex); // destroy renderer SDL_DestroyRenderer(rend); // destroy window SDL_DestroyWindow(win); return 0; } |
That will render a image on the window which can be controlled via your keyboard up, down, left, right.
Output:
References: https://www.libsdl.org/, https://github.com/vivek9236/rocket_game
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- ctype.h(<cctype>) library in C/C++ with Examples
- How to print range of basic data types without any library function and constant in C?
- Unordered Sets in C++ Standard Template Library
- Advanced C++ with boost library
- Inbuilt library functions for user Input | scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s
- How to add "graphics.h" C/C++ library to gcc compiler in Linux
- The C++ Standard Template Library (STL)
- List in C++ Standard Template Library (STL)
- Deque in C++ Standard Template Library (STL)
- Map in C++ Standard Template Library (STL)
- Wide char and library functions in C++
- C Library math.h functions
- isgraph() C library function
- difftime() C library function
- wcstof function in C library
- wprintf() and wscanf in C Library
- snprintf() in C library
- boost::split in C++ library
- <iterator> library in C++ STL
- Factorial of Large Number Using boost multiprecision Library
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : roshanr2001

