You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CMake配置SDL2?附我编写的SDL基础示例代码

Great to see you diving into SDL2! Configuring your project with CMake is a solid choice for cross-platform compatibility. Here's a step-by-step guide to get your "Hello World" SDL2 project up and running smoothly:

1. First, Install SDL2 Development Files

Before setting up CMake, make sure you have the SDL2 development libraries installed for your system:

  • On Ubuntu/Debian: Run sudo apt-get install libsdl2-dev
  • On Windows: Use a package manager like vcpkg (vcpkg install sdl2) or download prebuilt binaries from the SDL website and extract them to a known location.
  • On macOS: Use Homebrew with brew install sdl2

2. Create Your CMakeLists.txt

In the root of your project, add a CMakeLists.txt file with this content—it handles finding SDL2, compiling your code, and linking the library properly:

cmake_minimum_required(VERSION 3.10)
project(SDL_Hello_World)

# Locate the SDL2 package
find_package(SDL2 REQUIRED)

# Add your executable, pointing to your source file
add_executable(hello_sdl src/main.cpp)

# Link SDL2 to your executable (modern imported target handles headers + linking)
target_link_libraries(hello_sdl PRIVATE SDL2::SDL2)

Quick Notes on the Config:

  • find_package(SDL2 REQUIRED) tells CMake to locate SDL2. If you installed SDL2 in a non-standard path, specify it with -DSDL2_DIR=/path/to/your/sdl2 when running CMake.
  • The SDL2::SDL2 target automatically includes SDL2's header directories, so you don't need to add include_directories() manually.

3. Organize Your Project Structure

Keep your files clean with this simple layout:

your_project/
├── CMakeLists.txt
└── src/
    └── main.cpp  # Your existing SDL2 code goes here

4. Build and Run the Project

Open a terminal and run these commands from your project root:

# Create a build directory to keep source files clean
mkdir build && cd build

# Generate build files (use `-G "Visual Studio 17 2022"` on Windows if using VS)
cmake ..

# Compile the project
make  # Use "ninja" if you chose the Ninja generator, or build via VS on Windows

Once compiled, run your executable from the build directory:

./hello_sdl

Troubleshooting Tips

  • If CMake can't find SDL2: Double-check that development packages are installed correctly. For custom installations, pass the SDL2 path with -DSDL2_DIR during the CMake generation step.
  • On Windows: If using prebuilt SDL2 binaries, make sure the SDL2 DLL is in the same directory as your executable when running it.

内容的提问来源于stack exchange,提问作者Anmol Gautam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:22:29