如何使用CMake链接SDL2?

use*_*750 5 cmake include dynamic-linking sdl-2

我使用了https://github.com/brendan-w/collector/tree/master/cmake中的.cmake文件,并将它们放在与我的CMakeLists.txt相同的目录中,然后我使用了代码:

set(CMAKE_MODULE_PATH FindSDL2.cmake FindSDL2_image.cmake)
find_package(SDL2 REQUIRED)
Run Code Online (Sandbox Code Playgroud)

但是我收到了错误:

CMake Error at CMakeLists.txt:26 (find_package):
  By not providing "FindSDL2.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "SDL2", but
  CMake did not find one.

  Could not find a package configuration file provided by "SDL2" with any of
  the following names:

    SDL2Config.cmake
    sdl2-config.cmake

  Add the installation prefix of "SDL2" to CMAKE_PREFIX_PATH or set
  "SDL2_DIR" to a directory containing one of the above files.  If "SDL2"
  provides a separate development package or SDK, be sure it has been
  installed.
Run Code Online (Sandbox Code Playgroud)

squ*_*les 3

CMAKE_MODULE_PATH变量包含 CMake 模块的路径列表(FindSDL2.cmakeFindSDL2_image.cmake等是您的模块)。您应该将计算机上这些模块的完整路径附加到此变量中:

list(APPEND CMAKE_MODULE_PATH /path/to/your/SDL2/modules)
find_package(SDL2 REQUIRED)
Run Code Online (Sandbox Code Playgroud)

最近,SDL2提供了一个 CMake 配置文件,可用于帮助 CMake 找到您的 SDL2 安装。您的错误消息明确描述了这一点,并指出了包配置名称(SDL2Config.cmakesdl2-config.cmake)。要允许 CMake 使用此方法查找 SDL2,请使用CMAKE_PREFIX_PATH

list(APPEND CMAKE_PREFIX_PATH /path/to/your/SDL2/config/files)
find_package(SDL2 REQUIRED)
Run Code Online (Sandbox Code Playgroud)

一旦 CMake 找到包,它将定义一些SDL2_*可在 CMake 项目中使用的变量:

...

add_executable(MySDL2Executable main.cpp)
include_directories(MySDL2Executable PRIVATE ${SDL2_INCLUDE_DIRS})
target_link_libraries(MySDL2Executable PRIVATE ${SDL2_LIBRARIES})
Run Code Online (Sandbox Code Playgroud)

请注意,这些变量名称可能会因您的 SDL2 版本而异。SDL2_*请查阅 CMake 模块文件或包配置文件本身以获取定义的变量名称列表。