gpt4 book ai didi

c++ - CMake add_subdirectory 不调用子 CMakeLists.txt

转载 作者:行者123 更新时间:2023-11-30 02:27:48 26 4
gpt4 key购买 nike

我有一个这样的项目结构,我希望使用 CMake 构建它。

root\
|
|--crystal\
| |
| |--include\ Math.h, Window.h
| |--src\ Math.cpp, Window.cpp
| |--lib\
| |--CMakeLists.txt // the CHILD cmake
|
|--game\ main.cpp
|--CMakeLists.txt // the PARENT cmake

crystal 子项目应该在 lib/ 文件夹中生成一个静态库 (libcrystal.a)(使用内容include/src/) 和 root 项目将从 game/main.cpp 中生成可执行文件链接 libcrystal.a 静态库。

父CMAKE如下:

cmake_minimum_required(VERSION 2.8.1)
project(thegame)

set(CRYSTAL_LIB_DIR lib)
set(CRYSTAL_LIB_NAME crystal)

add_subdirectory(${CRYSTAL_LIB_NAME})

set(LINK_DIR ${CRYSTAL_LIB_NAME}/${CRYSTAL_LIB_DIR})

set(SRCS game/main.cpp)
link_directories(${LINK_DIR})
include_directories(${CRYSTAL_LIB_NAME}/include)

add_executable(thegame ${SRCS})
target_link_libraries(thegame lib${CRYSTAL_LIB_NAME}.a)

子CMAKE如下:

cmake_minimum_required(VERSION 2.8.1)

project(crystal)

include_directories( include )
file(GLOB_RECURSE SRC "src/*.cpp")

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CRYSTAL_LIB_DIR})
add_library(${CRYSTAL_LIB_NAME} STATIC ${SRC})

什么不起作用:

当我在 root/ 目录中执行 cmake .sudo make 时,我希望父 cmake 和子 cmake 依次运行。但似乎子 cmake 没有被调用,因此没有生成 .a 文件。它显示了一些错误,例如:

Scanning dependencies of target thegame
[ 20%] Building CXX object CMakeFiles/thegame.dir/game/main.cpp.o
[ 40%] Linking CXX executable thegame
/usr/bin/ld: cannot find -lcrystal
collect2: error: ld returned 1 exit status
CMakeFiles/thegame.dir/build.make:94: recipe for target 'thegame' failed
make[2]: *** [thegame] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/thegame.dir/all' failed
make[1]: *** [CMakeFiles/thegame.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

什么是有效的:

我继续做这个

  1. root/ 中执行 cmake .
  2. 导航到 crystal 文件夹并通过 sudo make 手动调用 Makefile>
  3. 再次来到root/,通过sudo make调用外层Makefile

非常有效

问题:

为什么子 CMake 没有像我在什么不工作部分提到的那样被调用???

最佳答案

在根 CMakeLists.txt 中使用 target_link_libraries(thegame ${CRYSTAL_LIB_NAME}) 并删除 link_directories 调用。 CMake 将识别您正在链接到 crystal 目标并相应地设置 makefile 依赖项和编译器标志。

关于c++ - CMake add_subdirectory 不调用子 CMakeLists.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com