我有一个CMake项目,如下所示:
project/
CMakeLists.txt
subprojectA/
CMakeLists.txt
include/
headerA.hpp
src/
libraryA.cpp
subprojectB/
CMakeLists.txt
src/
mainB.cpp
“library”子项目A被编译为静态库,成为libsubprojectA.a。 “主”项目B编译为二进制文件并依赖于库。 mainB.cpp包含对headerA.hpp的引用。
这是subprojectA / CMakeLists.txt:
project(SubProjectA)
include_directories(include)
add_library(subprojectA STATIC src/libraryA.cpp)
set(${PROJECT_NAME}_INCLUDE_DIRS
${PROJECT_SOURCE_DIR}/include
CACHE INTERNAL "${PROJECT_NAME}: Include Directories" FORCE)
这是subprojectB / CMakeLists.txt:
project(SubProjectB)
include_directories(${SubProjectA_INCLUDE_DIRS})
add_executable(mainBinary src/mainB.cpp)
target_link_libraries(mainBinary subprojectA)
主项目CMakeLists.txt如下所示:
project(Project)
add_subdirectory(subprojectB)
add_subdirectory(subprojectA)
请注意,主项目subprojectB在子项目A之前列出。
这是问题所在。当我第一次在此项目上运行“cmake”时,未在SubProjectB中设置${SubProjectA_INCLUDE_DIRS}
。
我认为发生的事情是,当尚未设置${SubProjectA_INCLUDE_DIRS}
时,首先加载SubProjectB的CMakeLists。它将自己的include路径设置为空字符串。但是,即使在libsubprojectA.a
之前成功构建了mainBinary
,包含路径也已预先设置为空。因此,在尝试制作mainBinary
时出现此错误:
subprojectB/src/mainB.cpp:1:23: fatal error: headerA.hpp: No such file or directory
#include "headerA.hpp"
^
将subprojectA之前的subprojectA放在CMake声明世界的主要Project CMakeLists中是一种解决方法。我真正想要的是知道正确的方法来向CMake表明include_directories(${SubProjectA_INCLUDE_DIRS})
行依赖于对SubProjectA的CMakeLists中存在的定义。有更好的方法吗?
答案 0 :(得分:1)
如果您想表示包含目录 subprojectA / include 是库子项目A 的接口,请将此属性附加到目标target_include_directories命令:
<强> subprojectA /的CMakeLists.txt 强>:
project(SubProjectA)
add_library(subprojectA STATIC src/libraryA.cpp)
# PUBLIC adds both:
# 1) include directories for compile library and
# 2) include directories for library's interface
target_include_directories(subprojectA PUBLIC include)
因此,与 subprojectA 链接的任何可执行文件(或其他库)都会自动包含此目录:
<强> subprojectB /的CMakeLists.txt 强>:
project(SubProjectB)
add_executable(mainBinary src/mainB.cpp)
target_link_libraries(mainBinary subprojectA)
当然,为了正确使用上一个命令,您需要使用库处理目录一个具有可执行文件的目录:
<强>的CMakeLists.txt 强>:
project(Project)
add_subdirectory(subprojectA)
add_subdirectory(subprojectB)