【问题标题】:CMake build target without specifying target_include_directories未指定 target_include_directories 的 CMake 构建目标
【发布时间】:2021-04-17 08:22:13
【问题描述】:

我有一个具有以下文件布局的项目:

Project
├── CMakeLists.txt
├── app
│   ├── CMakeLists.txt
│   └── main.cpp
└── ext
    ├──CMakeLists.txt
    └── lib
        ├── CMakeLists.txt
        ├── include
        │   └── foo.h
        └── foo.cpp

foo 是一个第三方库,我下载了我想在main.cpp 中使用的源代码。我可以使用以下 cmake 文件构建 main.cpp:

add_executable(app main.cpp)

target_include_directories(app PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/extern/foo/include)
target_link_libraries(app foo)

但是我觉得 foo 库应该有责任指定使用它时应该包含哪些文件。有没有办法在没有 target_include_directories 调用的情况下完成这项工作?

【问题讨论】:

  • 只需为foo 库添加带有适当参数的target_include_directories。所以这些包含目录会自动传播给这个库的用户。
  • 哇,这很容易。如果您发布答案,我可以接受。我是否正确假设在这种情况下 INTERFACE 是 lib 的正确包含关键字?既然 main.cpp 不应该传播它?
  • 如果您的foo 库不使用foo.h 标头,那么INTERFACE 是正确的关键字。但很可能foo 库实际上使用了foo.h 标头,在这种情况下PUBLIC 是正确的。

标签: cmake


【解决方案1】:

只需添加

target_include_directories(foo PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)

转入extern/foo/CMakeLists.txt

这样,当您构建 foo 库时以及与该库链接的任何人都可以访问包含目录。


请注意,包含目录和其他库属性的自动传播仅在您与库目标链接时有效:

# Assuming you have 'add_library(foo)' somewhere,
# PUBLIC and INTERFACE properties of the `foo` library will be propagated
# to the 'app'.
target_link_libraries(app PUBLIC foo)

即使在target_link_libraries 调用之后发出add_library(foo),这也会起作用。

与库文件链接时无法传播:

# Propagation won't work with a name of the library file:
target_link_libraries(app PUBLIC foo.a)
# Propagation won't work with a full path to the library file:
target_link_libraries(app PUBLIC /path/to/foo.a)
# If 'add_library(foo)' in inaccessible from the project,
# then linking with 'foo' means linking with a library file,
# so propagation won't work.
target_link_directories(app PUBLIC /path/to/)
target_link_libraries(app PUBLIC foo)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2016-08-02
    • 1970-01-01
    • 2014-12-02
    相关资源
    最近更新 更多