【问题标题】:How do I correctly create dependencies between targets in CMake?如何在 CMake 中正确创建目标之间的依赖关系?
【发布时间】:2011-06-21 18:19:22
【问题描述】:

我正在尝试使用 CMake 在 C++ 项目与其使用的库之间建立一些简单的依赖关系。

设置如下

  • 项目
    • 依赖关系

项目本身包含包含来自Dependency 的标头的源文件,并且在构建可执行文件时,它需要链接到Dependency 的静态库。

到目前为止,我可以让它工作,但我必须在 CMakeLists.txt 文件中手动为 Project 指定 Dependency 的包含目录。我希望自动将其拉出,并且我已经探索了使用 find_package() 命令的选项,但成功有限,并使事情变得更加复杂。

我想要做的就是在Project 之前构建Dependency 并让Project 链接到库并拥有它的包含目录。有没有一种简单简洁的方法来实现这一点?

我当前的 CMake 文件:

Project,文件CMakeLists.txt

cmake_minimum_required (VERSION 2.6)
project (Project)
include_directories ("${PROJECT_SOURCE_DIR}/Project")
add_subdirectory (Dependency)
add_executable (Project main.cpp)
target_link_libraries (Project Dependency)
add_dependencies(Project Dependency)

Dependency,文件CMakeLists.txt

project(Dependency)
add_library(Dependency SomethingToCompile.cpp)
target_link_libraries(Dependency)

【问题讨论】:

标签: c++ build cmake


【解决方案1】:

由于CMake 2.8.11,您可以使用target_include_directories。只需在您的 DEPENDENCY 项目中添加此功能并填写您希望在主项目中看到的包含目录即可。 CMake 会关心其余的。

项目,CMakeLists.txt:

cmake_minimum_required (VERSION 2.8.11)
project (Project)
include_directories (Project)
add_subdirectory (Dependency)
add_executable (Project main.cpp)
target_link_libraries (Project Dependency)

依赖,CMakeLists.txt

project (Dependency)
add_library (Dependency SomethingToCompile.cpp)
target_include_directories (Dependency PUBLIC include)

【讨论】:

  • add_subdirectory 总是计算Dependency,不管它是否被引用。你如何表达它,只有当Projecttarget_link_libraries 中引用它时才会计算Dependency
【解决方案2】:

不清楚你想做什么,为什么ProjectDependency必须分开构建。

我的第一个例子是

  1. PROJECTCMakeLists.txt

    • 删除add_dependencies(Project Dependency) 不需要指定依赖,target_link_libraries() 已经做到了。
  2. DEPENDENCYCMakeLists.txt

    • 删除project(Dependency) 它建立了一个库,那为什么还要有自己的项目呢?
    • 删除target_link_libraries(Dependency) 因为它什么都不做

【讨论】:

  • 回答您的问题。依赖项可能是作为 git 子模块包含的共享库的项目。共享库也可以在没有外部项目的情况下工作。
猜你喜欢
  • 2012-02-22
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
  • 2014-07-17
  • 1970-01-01
  • 2019-10-28
相关资源
最近更新 更多