如何使用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/sdl2when running CMake.- The
SDL2::SDL2target automatically includes SDL2's header directories, so you don't need to addinclude_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_DIRduring 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




