c++ - 如何在 CMake 中正确创建目标之间的依赖关系?

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

设置如下

  • 项目
    • 依赖

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

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

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

我当前的 CMake 文件:

项目,文件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)

依赖,文件CMakeLists.txt:

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

最佳答案

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)

https://stackoverflow.com/questions/4905089/

相关文章:

haskell - 使用 cabal 和 ghc 构建运行时标志

Xcode - 自动将文件夹中的所有文件添加到目标

java - 在 Eclipse 中使用 Ant 时出现错误运行 javac.exe 编译器消息

visual-studio - Visual Studio 2008 不必要的项目构建

asp.net - Web.config 构建与发布转换不起作用

c - 如何链接到 C 中的静态库?

c - getopt.h : Compiling Linux C-Code in Windows

javascript - 如何防止 Visual Studio 2017 构建 JavaScript

c# - 通过命令行构建 Visual Studio 项目

c - 如何在 Go 中构建发布版本的二进制文件?