SFML Desktop: Setup with find_package (MinGW 13.1) SFML для Desktop: Настройка через find_package (MinGW 13.1)
A guide to configuring SFML with CMake and MinGW on Windows. Руководство по настройке SFML с использованием CMake и MinGW на Windows.
1. Obtain SFML 2.6.2 1. Получение SFML 2.6.2
- Download my pre-built version of SFML 2.6.2 for MinGW 13.1 (WinLibs): SFML-2.6.2-mingw.zip Скачайте мою готовую сборку SFML 2.6.2 для MinGW 13.1 (WinLibs): SFML-2.6.2-mingw.zip
- Alternatively, you can build it yourself following my guide: Building SFML 2.6.2 from Source Или же вы можете собрать её самостоятельно по моей инструкции: Сборка SFML 2.6.2 из исходников
-
Extract the archive so the path is exactly
C:/libs/SFML-2.6.2-mingwРаспакуйте архив так, чтобы путь был именноC:/libs/SFML-2.6.2-mingw
2. Add SFML to System PATH 2. Добавление SFML в системный PATH
To ensure your applications can find the SFML .dll files at runtime, you should add the library's bin folder to your Environment Variables:
Чтобы приложения могли находить .dll файлы SFML при запуске, необходимо добавить папку bin библиотеки в переменные среды:
C:\libs\SFML-2.6.2-mingw\bin
3. Project Configuration (CMakeLists.txt) 3. Конфигурация проекта (CMakeLists.txt)
-
Create a new empty folder for your project (e.g.,
rectangle-sfml2-cpp). Создайте новую пустую папку для вашего проекта (например,rectangle-sfml2-cpp). -
Inside that folder, create a file named
CMakeLists.txtand paste the following content: Внутри этой папки создайте файл с именемCMakeLists.txtи вставьте следующее содержимое:
cmake_minimum_required(VERSION 3.21)
project(rectangle-sfml2-cpp)
set(SFML_DIR "C:/libs/SFML-2.6.2-mingw/lib/cmake/SFML")
find_package(SFML 2.6 COMPONENTS system window graphics REQUIRED)
# Define the executable
add_executable(app)
target_sources(app
PRIVATE
src/main.cpp
)
target_link_libraries(app sfml-system sfml-window sfml-graphics)
# This code copies the SFML DLLs to the build directory
add_custom_command(TARGET app POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
$<TARGET_RUNTIME_DLLS:app> $<TARGET_FILE_DIR:app>
COMMAND_EXPAND_LISTS
)
# Copy Assets (ONLY if the folder exists!)
if(EXISTS "${CMAKE_SOURCE_DIR}/assets")
add_custom_command(TARGET app POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${CMAKE_SOURCE_DIR}/assets" "$<TARGET_FILE_DIR:app>/assets"
)
endif()
target_link_options(app PRIVATE -mconsole)
4. Source Code (src/main.cpp) 4. Исходный код (src/main.cpp)
-
Create a folder named
srcin your project root. Создайте папкуsrcв корне вашего проекта. -
Inside the
srcfolder, create a file namedmain.cppwith the following content: Внутри папкиsrcсоздайте файл с именемmain.cppсо следующим содержимым:
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(400, 300), "SFML2 Rotated Rectangle");
sf::RectangleShape rectangle(sf::Vector2f(150.f, 50.f));
rectangle.setFillColor(sf::Color::Green);
// Set the origin to the center of the rectangle
rectangle.setOrigin(75.f, 25.f);
rectangle.setPosition(200.f, 150.f);
rectangle.setRotation(20.f);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(rectangle);
window.display();
}
return 0;
}
5. Opening the Project in IDEs 5. Открытие проекта в IDE
CLion
-
Go to File > Open and select the project folder containing your
CMakeLists.txtПерейдите в File > Open и выберите папку проекта, содержащуюCMakeLists.txt - When prompted, click Open as Project. CLion will automatically detect the CMake configuration. При появлении запроса нажмите Open as Project. CLion автоматически обнаружит конфигурацию CMake.
Qt Creator
-
Go to File > Open File or Project and select the
CMakeLists.txtfile. Перейдите в File > Open File or Project и выберите файлCMakeLists.txt. - In the "Configure Project" tab, ensure your Desktop Qt MinGW kit is selected and click Configure Project. На вкладке "Configure Project" убедитесь, что выбран комплект Desktop Qt MinGW, и нажмите Configure Project.
Sublime Text 4 + CMD
- Open Sublime Text and drag-and-drop the project folder into the editor. Откройте Sublime Text и перетащите папку проекта в редактор.
- Open a Command Prompt (CMD) in the project root directory. Откройте командную строку (CMD) в корневой директории проекта.
6. Automation Scripts 6. Скрипты автоматизации
Create these .bat files in your project root to speed up development: Создайте эти .bat файлы в корне проекта для ускорения разработки:
config-exe.bat
cmake -G "MinGW Makefiles" -S . -B dist/win ^
-DCMAKE_BUILD_TYPE=Debug
build-exe.bat
cd dist\win
cmake --build .
cd ..\..
run-exe.bat
dist\win\app
7. How to Build and Run 7. Как собрать и запустить
-
To build and run from the CMD (recommended for Sublime Text), use:
Чтобы собрать и запустить через CMD (рекомендуется для Sublime Text), используйте:
config-exe
build-exe
run-exe - In CLion or Qt Creator, simply press the Run button (green arrow) to compile and start the app. В CLion или Qt Creator просто нажмите кнопку Run (зеленая стрелка), чтобы скомпилировать и запустить приложение.
8. GitHub Template 8. Шаблон на GitHub
You can find the complete source code and project structure for this guide here: setting-up-sfml-with-find-package Вы можете найти полный исходный код и структуру проекта для этого руководства здесь: setting-up-sfml-with-find-package
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 Поддержка криптовалютой