SDL3 Desktop: Setup for C and C++ (MinGW 13.1) SDL3 для Desktop: Настройка для C и C++ (MinGW 13.1)
A guide to configuring SDL3 with CMake and MinGW on Windows for both C and C++. Руководство по настройке SDL3 с использованием CMake и MinGW на Windows для C и C++.
1. Obtain SDL 3.4.10 1. Получение SDL 3.4.10
-
Download two archives from the official release page:
Скачайте два архива со страницы официального релиза:
-
Extract the SDL3-devel-3.4.10-mingw.zip archive to the
C:/libs/SDL3-devel-3.4.10-mingwfolder. Распакуйте архив SDL3-devel-3.4.10-mingw.zip в папкуC:/libs/SDL3-devel-3.4.10-mingw. -
Move the headers and libraries so the structure is
SDL3-devel-3.4.10-mingw/include, etc: Переместите заголовочные файлы и библиотеки так, чтобы структура папок былаSDL3-devel-3.4.10-mingw/includeи т. д.:
-
Extract the SDL3-3.4.10-win32-x64.zip archive so the path is exactly
C:/libs/SDL3-3.4.10-win32-x64: Распакуйте архив SDL3-3.4.10-win32-x64.zip так, чтобы путь был именноC:/libs/SDL3-3.4.10-win32-x64:
2. Add SDL3 to Environment Variables (Path) 2. Добавление SDL3 в переменные среды (Path)
To ensure your applications can find the SDL3.dll file at runtime, you should add the following path to the Path variable in your User variables section:
Чтобы приложения могли находить SDL3.dll файл при запуске, добавьте следующий путь в переменную Path в разделе Переменные среды пользователя:
C:\libs\SDL3-3.4.10-win32-x64
3. Project Structure 3. Структура проекта
C Project: Create an empty folder named rectangle-sdl3-c and set up the following hierarchy by creating new CMakeLists.txt and main.c files:
Проект на C: Создайте пустую папку с именем rectangle-sdl3-c и подготовьте следующую иерархию, создав файлы CMakeLists.txt и main.c:
rectangle-sdl3-c/
├── CMakeLists.txt
└── src/
└── main.c
C++ Project: Create an empty folder named rectangle-sdl3-cpp and set up the following hierarchy by creating new CMakeLists.txt and main.cpp files:
Проект на C++: Создайте пустую папку с именем rectangle-sdl3-cpp и подготовьте следующую иерархию, создав файлы CMakeLists.txt и main.cpp:
rectangle-sdl3-cpp/
├── CMakeLists.txt
└── src/
└── main.cpp
Follow the steps below to create the CMakeLists.txt and the source files in the src directory with the provided content.
Следуйте шагам ниже, чтобы создать файл CMakeLists.txt и исходные файлы в директории src с указанным содержимым.
4. Project Configuration (CMakeLists.txt) 4. Конфигурация проекта (CMakeLists.txt)
C Project: Copy and paste the following code into the CMakeLists.txt file:
Проект на C: Скопируйте и вставьте следующее содержимое в файл CMakeLists.txt:
CMakeLists.txt (C version)
set(CMAKE_BUILD_TYPE "Debug")
cmake_minimum_required(VERSION 3.21)
project(rectangle-sdl3-c)
set(SDL3_DIR "C:/libs/SDL3-devel-3.4.10-mingw/lib/cmake/SDL3")
find_package(SDL3 REQUIRED)
add_executable(app)
target_sources(app
PRIVATE
src/main.c
)
target_link_libraries(app PRIVATE SDL3::SDL3)
target_link_options(app PRIVATE -mconsole)
C++ Project: Copy and paste the following code into the CMakeLists.txt file:
Проект на C++: Скопируйте и вставьте следующее содержимое в файл CMakeLists.txt:
CMakeLists.txt (C++ version)
set(CMAKE_BUILD_TYPE "Debug")
cmake_minimum_required(VERSION 3.21)
project(rectangle-sdl3-cpp)
set(SDL3_DIR "C:/libs/SDL3-devel-3.4.10-mingw/lib/cmake/SDL3")
find_package(SDL3 REQUIRED)
add_executable(app)
target_sources(app
PRIVATE
src/main.cpp
)
target_link_libraries(app PRIVATE SDL3::SDL3)
target_link_options(app PRIVATE -mconsole)
5. Source Code 5. Исходный код
Copy and paste the following code into the src/main.c (or src/main.cpp) file:
Скопируйте и вставьте следующее содержимое в файл src/main.c (или src/main.cpp):
main.c / main.cpp
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
int main(int argc, char* argv[])
{
if (!SDL_Init(SDL_INIT_VIDEO)) {
return -1;
}
SDL_Window* window = SDL_CreateWindow("SDL3 C", 400, 300, 0);
SDL_Renderer* renderer = SDL_CreateRenderer(window, NULL);
bool running = true;
SDL_Event event;
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_EVENT_QUIT) {
running = false;
}
}
SDL_SetRenderDrawColor(renderer, 20, 20, 20, 255);
SDL_RenderClear(renderer);
SDL_FRect rect = { 125.0f, 125.0f, 150.0f, 50.0f };
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_RenderFillRect(renderer, &rect);
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
6. Opening the Project in IDEs 6. Открытие проекта в IDE
Open the CMakeLists.txt file in CLion or Qt Creator. CMake will handle the rest. Откройте файл CMakeLists.txt в CLion или Qt Creator. CMake позаботится об остальном.
7. Automation Scripts (.bat) 7. Скрипты автоматизации (.bat)
You can open the project folder in Sublime Text 4 (or Notepad++). Create the following .bat scripts in the project root directory to automate the configuration, building, and running of your application:
Вы можете открыть папку проекта в Sublime Text 4 (или Notepad++). Создайте следующие .bat скрипты в корневой директории проекта для автоматизации конфигурации, сборки и запуска вашего приложения:
1. config-exe.bat
cmake -G "MinGW Makefiles" -S . -B dist/exe
2. build-exe.bat
cd dist\exe
cmake --build .
cd ..\..
3. run-exe.bat
dist\exe\app
To build and launch the application, run these scripts in the terminal in the following order:
Чтобы собрать и запустить приложение, выполните эти скрипты в терминале в следующем порядке:
config-exe
build-exe
run-exe
8. Alternative: SDL3 Callback System 8. Альтернатива: Система Callbacks в SDL3
SDL3 introduces a modern callback-based approach. Instead of a while loop, you define specific functions that SDL calls when needed. This is the preferred method for Web (Emscripten) and Mobile platforms.
В SDL3 представлен современный подход на основе обратных вызовов (callbacks). Вместо цикла while вы определяете специальные функции, которые SDL вызывает по мере необходимости. Это рекомендуемый метод для Web (Emscripten) и мобильных платформ.
| Function | Description Описание |
|---|---|
SDL_AppInit |
Called once at startup. Initialize SDL, create window, and load assets here. Вызывается один раз при запуске. Инициализация SDL, окна и загрузка ресурсов. |
SDL_AppEvent |
Called whenever a new event (keyboard, mouse, quit) occurs. Вызывается каждый раз, когда происходит событие (клавиатура, мышь, выход). |
SDL_AppIterate |
The "Heartbeat". Called every frame. Put your rendering and logic here. "Сердцебиение" программы. Вызывается каждый кадр. Здесь происходит рендеринг. |
SDL_AppQuit |
Called before exiting. Clean up and free memory here. Вызывается перед выходом. Очистка и освобождение памяти. |
main.c / main.cpp (Callback Version)
#define SDL_MAIN_USE_CALLBACKS 1 // Use callback functions instead of main()
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
// We will use this renderer to draw into this window every frame
static SDL_Window *window = NULL;
static SDL_Renderer *renderer = NULL;
// This function runs once at startup
SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[])
{
if (!SDL_Init(SDL_INIT_VIDEO))
{
SDL_Log("Couldn't initialize SDL: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
if (!SDL_CreateWindowAndRenderer("SDL3 Rectangles", 500, 500, SDL_WINDOW_RESIZABLE, &window, &renderer))
{
SDL_Log("Couldn't create window/renderer: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
SDL_SetRenderVSync(renderer, 1);
return SDL_APP_CONTINUE; // Continue program execution!
}
// This function runs whenever a new event occurs (mouse input, key presses, etc.)
SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event)
{
if (event->type == SDL_EVENT_QUIT)
{
return SDL_APP_SUCCESS; // Terminate the program, reporting success to the OS
}
return SDL_APP_CONTINUE; // Continue program execution!
}
// This function runs once per frame and is the heart of the program
SDL_AppResult SDL_AppIterate(void *appstate)
{
SDL_SetRenderDrawColor(renderer, 38, 43, 51, 255);
// Clear the window with the draw color
SDL_RenderClear(renderer);
SDL_FRect rect;
rect.x = 100;
rect.y = 50;
rect.w = 200;
rect.h = 60;
SDL_SetRenderDrawColor(renderer, 220, 80, 80, SDL_ALPHA_OPAQUE);
SDL_RenderFillRect(renderer, &rect);
// Present the freshly cleared result to the screen
SDL_RenderPresent(renderer);
return SDL_APP_CONTINUE; // Continue program execution!
}
// This function runs once upon shutdown
void SDL_AppQuit(void *appstate, SDL_AppResult result)
{
// SDL will clean up the window and renderer for us
}
Support My Work Поддержать проект
If these tutorials helped you, consider buying me a coffee! Если эти туториалы вам помогли, вы можете поддержать автора.
Sberbank
Direct transfer via phone number Перевод по номеру телефона
Bybit (USDT TRC20)
Support via Cryptocurrency Поддержка криптовалютой