假设我使用了 find_package(SDL REQUIRED) 现在我需要通过 target_link_libraries 链接到该库 要传递给 target_link_libraries 的变量名称是什么?一般来说,除了启发式猜测之外,还有其他方法可以找到这些变量吗?我尝试过 SDL_LIBRARY、SDL2_LIBRARY 和 SDL_LIBRARIES。我确实安装了 sdl2。
我本以为这会起作用,但它没有:
cmake_minimum_required(VERSION 3.10)
project(someProject)
# Find SDL2
find_package(SDL REQUIRED)
find_package(SDL_image REQUIRED)
# Include directories
include_directories(${SDL2_INCLUDE_DIRS} ${SDL2_IMAGE_INCLUDE_DIRS})
# Set source files
set(SOURCES main.cpp)
# Set executable
add_executable(someProject ${SOURCES})
# Link libraries
target_link_libraries(someProject ${SDL2_LIBRARIES} ${SDL2_IMAGE_LIBRARIES})
我明白了
CMake 错误位于
/usr/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:230
(message):
Could NOT find SDL (missing: SDL_LIBRARY SDL_INCLUDE_DIR)
Call Stack (most recent call first):
/usr/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:600 (_FPHSA_FAILURE_MESSAGE)
/usr/share/cmake/Modules/FindSDL.cmake:224 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
CMakeLists.txt:5 (find_package)
-- Configuring incomplete, errors occurred!
答案1
它是通常 <MODULENAME>_LIBRARIES
,SDL 也是如此。
但这只是约定,您可能需要阅读相应的find_<MODULENAME>.cmake
脚本(通常在 /usr/share/cmake/Modules、/usr/lib/cmake/version/Modules 或源树的一部分等位置)。遗憾的是,尤其是在连字符、大写和其他命名细微差别方面,这些 CMake 模块简直就是狂野西部。您要么从库作者那里获得良好的文档,要么需要阅读find_<MODULENAME>.cmake
.
也不是说您不应该使用在 CMake 中使用库的旧方法。而不是你的
# Find SDL2
find_package(SDL REQUIRED)
find_package(SDL_image REQUIRED)
# Include directories
include_directories(${SDL2_INCLUDE_DIRS} ${SDL2_IMAGE_INCLUDE_DIRS})
# Set source files
set(SOURCES main.cpp)
# Set executable
add_executable(someProject ${SOURCES})
# Link libraries
target_link_libraries(someProject ${SDL2_LIBRARIES} ${SDL2_IMAGE_LIBRARIES})
你应该只使用现代CMake,这让事情变得简单。如果你只需要SDL2(而不是SDL2_image),那么你的整个发现和使用就变成这样:
# Find SDL2, which has modern CMake bindings
find_package(SDL REQUIRED)
# Set executable
add_executable(someProject main.cpp)
# Link libraries (I assume you want PRIVATE here, `someProject` is not supposed to export SDL targets/symbols)
target_link_libraries(someProject PRIVATE SDL::SDL)
您不必自己设置包含目录,它们会自动设置,因为您将目标链接SDL::SDL
到Find_SDL.cmake
.
然而,您需要SDL2_image
(您确定吗?我认为现在它是 SDL 的一部分,但我可能是错的),而这并没有得到太多的喜爱,所以我们需要自己进行现代 CMake 设置。优点是我们只执行一次,从那时起,我们总是可以只使用我们设置的一次目标,而不必摆弄target_include_…
东西。
# Find SDL2, which has modern CMake bindings
find_package(SDL REQUIRED)
# SDL_image is legacy, so that's annoying, we have to fix things ourselves:
find_package(SDL_image REQUIRED)
if(NOT TARGET SDL::image)
add_library(SDL::image INTERFACE IMPORTED)
set_target_properties(SDL::image PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${SDL_IMAGE_INCLUDE_DIRS}"
INTERFACE_LINK_LIBRARIES "${SDL_IMAGE_LIBRARIES}")
endif()
# Set executable
add_executable(someProject main.cpp)
# Link libraries
target_link_libraries(someProject PRIVATE SDL::SDL SDL::image)
就是这样;无需记住多个变量名称,只需记住链接目标的名称:SDL::SDL
以及我们自己的SDL::image
.