【问题标题】:How to access headers in an include directory from headers in another include directory?如何从另一个包含目录中的标头访问包含目录中的标头?
【发布时间】:2019-06-12 10:53:29
【问题描述】:

我正在尝试在一个目标中使用 target_include_directories 包含多个目录,但一个包含目录中的标头无法访问另一个包含目录中的标头。我该如何解决这个问题?

我尝试将头文件放入 add_library,但没有帮助。 我刚才也在这里搜索了两个小时,但我似乎找不到任何相关信息。

顺便说一句,我正在使用 VC++。

下面的工程是简化的,真正的工程是here。

项目结构:

project
|-- CMakeLists.txt
|-- include
|   |-- project_header.h
|-- subproject
|   |-- CMakeLists.txt
|   |-- include
|   |   |-- subproject_header.h
|   |-- ...
|-- ...

project/CMakeLists.txt:

project("example")
add_subdirectory("subproject")

project/subproject/CMakeLists.txt:

add_executable(example "${PROJECT_SOURCE_DIR}/subproject/source/main.hpp")
set_target_properties(example PUBLIC_HEADER "${PROJECT_SOURCE_DIR}/subproject/include/subproject_header.h" PRIVATE_HEADER "${PROJECT_SOURCE_DIR}/include/project_header.h"
target_include_directories(example PUBLIC "include" PRIVATE "${PROJECT_SOURCE_DIR}/include")

问题是当我把它输入project/subproject/include/subproject_header.h:

...
#include "project_header.h"
...

这会产生错误:fatal error C1083: Cannot open include file: 'project_header.h': No such file or directory

我该如何解决这个问题?

编辑:

在使用.. 而不是${PROJECT_SOURCE_DIR} 后,问题似乎已自行解决。然后我把它改回${PROJECT_SOURCE_DIR},它仍然有效。这和缓存有关吗?

【问题讨论】:

  • @Evg 我没有测试就输入了代码,所以我输入了完整的路径以防冒险。此外,显示的项目是一个简化的项目,非常接近真实项目,但我不会在我的真实项目中输入完整路径。我确实使用了add_subdirectory。
  • 您可以运行make VERBOSE=1 并查看哪些目录进入-I 选项。
  • 我只在project/CMakeLists.txt中使用project。我已经编辑了帖子以明确这一点。
  • 我刚刚复制了您的示例,无法重现该问题。 -I<prefix>/subproject/include -I<prefix>/include 选项被传递给编译器。
  • 我会选择target_include_directories(example PRIVATE "${PROJECT_CURRENT_BINARY_DIR}/../include")

标签: c++ cmake


【解决方案1】:

假设我的项目是这样的:

project
|---include
|   |---common.h
|---library
|---executable

project/CMakeLists.txt:

project(example)
add_subdirectory(library)
add_subdirectory(executable)

project/library/CMakeLists.txt:

add_library(lib ...)
target_include_directories(lib PRIVATE "../include")

project/executable/CMakeLists.txt:

add_executable(exe ...)
target_link_libraries(exe lib)

如果我尝试从executable 中的文件访问common.h,那么编译器会报出上述错误。这是因为 PRIVATE 包含标头不会包含在其依赖项中。

解决办法是把这个加到project/projectB/CMakeLists.txt:target_include_directories(exe PRIVATE "../include")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-14
    • 2011-11-26
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 2020-03-21
    相关资源
    最近更新 更多