编译错误使用CMake与库[关闭]

rks48beu  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(115)

已关闭此问题为not reproducible or was caused by typos。它目前不接受回答。

此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题可能是on-topic在这里,这一个是解决的方式不太可能帮助未来的读者。
2个月前关闭。
Improve this question
我正在尝试创建一个有两个目标的CMake项目。其中一个必须是库,另一个必须是可执行文件。但是当我尝试构建可执行文件时,我得到一个错误,说找不到库。
库CMake:

file(GLOB SOURCES ${CMAKE_CURRENT_LIST_DIR}/src/*.cpp)

set(HEADERS include)

add_library(arcade-lib STATIC ${SOURCES})

target_include_directories(arcade-lib PUBLIC ${HEADERS})
target_link_libraries(arcade-lib PRIVATE sfml-window sfml-graphics)

可执行CMake:

file(GLOB SOURCES ${CMAKE_CURRENT_LIST_DIR}/src/*.cpp)
set(INCLUDE include)

set(ARCADE_GAMES_LIB_INCLUDE ../arcade-games-lib/include)

add_executable(snake-game snake-game.cpp ${SOURCES})

target_link_libraries(snake-game PRIVATE arcade-games-lib sfml-graphics sfml-window sfml-system sfml-main )
target_include_directories(snake-game PRIVATE ${INCLUDE} ${ARCADE_GAMES_LIB_INCLUDE})

主CMake:

cmake_minimum_required(VERSION 3.25)
project(arcade_games)

set(CMAKE_CXX_STANDARD 20)

set(CMAKE_EXE_LINKER_FLAGS "-static -static-libgcc")
set(SFML_STATIC_LIBRARIES TRUE)

find_package(SFML 2.5 COMPONENTS graphics window system REQUIRED)

add_subdirectory(arcade-games-lib)

add_subdirectory(snake-game)

错误消息:

C:\Program Files\JetBrains\CLion 2022.3.2\bin\mingw\bin/ld.exe: cannot find -larcade-games-lib
collect2.exe: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

我不知道该怎么办,因为一切看起来都很正常。我期望生成一个包含我的库的可执行文件

wbgh16ku

wbgh16ku1#

正如注解中指出的那样,问题在于add_librarytarget_link_libraries中的库的名称需要匹配。
正如@Botje和Why is cmake file GLOB evil?中指出的那样,使用file(GLOB收集源文件是有问题的
我冒昧地从你的CMakeLists.txt中删除了一些臃肿的内容:
库CMake:

add_library(arcade-lib STATIC 
  src/foo.cpp
  src/bar.cpp
  include/my_header.h # the compiler will work without it but headers may not show up in IDEs
)

target_include_directories(arcade-lib PUBLIC include) # no need for a variable, just use relative path
target_link_libraries(arcade-lib PRIVATE sfml-window sfml-graphics)

可执行CMake:

# no need for ARCADE_GAMES_LIB_INCLUDE once you specify the right library name

add_executable(snake-game 
  snake-game.cpp
  src/more_snake.cpp
)

# use the same library name you used in add_library:
target_link_libraries(snake-game PRIVATE arcade-lib sfml-graphics sfml-window sfml-system sfml-main)
target_include_directories(snake-game PRIVATE include)

相关问题