长话短说
使用 CMake,如何将子目录包含到库中,以便在不引用它们所在的目录的情况下包含它们?
结束 TL;DR
为了尽量简明扼要并以更高层次的方式谈论什么和如何,我删除了所有我认为不必要的细节。如果需要,我会进行编辑。因此,这是我的项目结构的简要介绍。
ParentDir
--src
----source.cpp
----source.h
----entities_dir
------entity.cpp
------entity.h
------CMakeLists.txt
----CMakeLists.txt
--CMakeLists.txt
--main.cpp
就目前而言,我在 src 目录中有一个由 CMakeLists 定义的库。因此,我可以通过 #include 在 main 中包含 src 文件,而不是 #include "src/file.h"我希望能够对存在于 src 的子目录中的 header 执行相同的操作。
CMakeLists.txt
cmake_minimum_required(VERSION 3.6)
project(Project)
add_executable(Project ${SOURCE_FILES} main.cpp)
include_directories(src)
add_subdirectory(src)
target_link_libraries(Project Library) # Engine Libraries
src/CMakeLists.txt
file(GLOB SOURCE_FILES *.cpp)
file(GLOB HEADER_FILES *.h)
add_library(Library STATIC ${SOURCE_FILES} ${HEADER_FILES})
main.cpp
#include <source.h> // this works
#include <entity.h> // this does not work but I want it to
#include <entities/entity.h> // this works but I don't want this
int main() {}
我不确定该怎么做。我尝试过 GLOB_RECURSE、add_subdirectory(entities) 等。我还尝试在 src/entities/CMakeLists.txt 中创建一个名为 Entities 的库,并将其与 link_libraries 链接。这些都没有成功。完成此任务的正确方法是什么,因为我认为我可能完全错误地处理了这个问题。
最佳答案
您的编译器 header 搜索路径中需要该路径,这是通过调用 include_directories() 实现的。您可以将现有的 include_directories(src) 调用修改为:
include_directories(src src/entities)
此外,这篇 SO 帖子是相关的,值得一读:Recursive CMake search for header and source files . CMake 网站本身有一段摘录,建议不要使用 file(GLOB ...),这通常会建议不要使用递归解决方案。作为 CMake 的重度用户,我同意反对它的论点。
关于c++ - CMake 添加带有子目录的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42322171/