Getting Started#
Environment: MacOS
The language used for developing SDL in this article is C language (don't ask, I just don't like C++).
This article is more of a technical record rather than a beginner's tutorial, but I think those who have some knowledge of C language should have no problem understanding it.
To download SDL on MacOS is very simple. Since I don't want to use Xcode, I directly use brew to download it and develop with VScode, which is very convenient.
brew install sdl2
After downloading, you also need to configure CMake. In MacOS, CMake cannot find the SDL library directly, so you need to link the header file location.
Use brew info
to find the library location.
brew info sdl2
After that, you can directly reference SDL by configuring CMake.
cmake_minimum_required(VERSION 3.23.2)
project(HelloSDL2 C)
set(CMAKE_C_STANDARD 11)
set(MY_LIBRARY_DIR /usr/local/Cellar)
set(SDL_DIR ${MY_LIBRARY_DIR}/sdl2/2.26.0)
include_directories(${SDL_DIR}/include/SDL2)
link_directories(${SDL_DIR}/lib/)
link_libraries(SDL2)
add_executable(HelloSDL2 main.c)
Alright, now you can start writing code!
Hello, SDL#
Creating a window in SDL is very simple. First, create a window.
#include <SDL.h>
int main() {
if (SDL_Init(SDL_INIT_VIDEO)) {
SDL_Log("Can not init video, %s", SDL_GetError());
return 1;
}
...
return 0;
}
The if
statement is to prevent problems in case you don't know what went wrong.
Then, configure the SDL window.
...
SDL_Window * win = SDL_CreateWindow(
//title
"HelloWorld",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
//window size
400,300,
SDL_WINDOW_SHOWN
);
....
Finally, don't forget to release the window.
...
SDL_DestroyWindow(win);
...
Complete code:
#include <SDL.h>
int main() {
if (SDL_Init(SDL_INIT_VIDEO)) {
SDL_Log("Can not init video, %s", SDL_GetError());
return 1;
}
SDL_Window * win = SDL_CreateWindow(
"HelloWorld",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
400,300,
SDL_WINDOW_SHOWN
);
if (win==NULL) {
SDL_Log("Can not create window, %s", SDL_GetError());
return 1;
}
SDL_Delay(3000);
SDL_DestroyWindow(win);
return 0;
}
If everything is fine, you will see a black window with a size of 400*300, which will automatically close after 3 seconds. On a Mac, you may not see anything, but you will notice a new program appearing in the dock, which means it was successful.
References#
SDL2 C Language Cross-platform Game Development Basics by Teacher Chen Yun
SDL2/FrontPage