如何通过 cmake 共享子目录中的标头和库

How do I share headers and libraries in subdirectory by cmake?

本文关键字:何通过 cmake 共享 子目录      更新时间:2023-10-16

我想将我的标头和库用作 app1 和 app2 的公共库。我的项目树在下面。 image/math/ 是 app1 和 app2 使用的库目录。在这种情况下,我是否应该为 app1 和 app2 下的CmakeLists.txt设置相同的设置?我当然知道它有效,但是有没有更聪明的方法来设置公共库?

|-- CMakeLists.txt
|-- app1
|   |-- CMakeLists.txt
|   `-- main.cc
|-- app2
|   |-- CMakeLists.txt
|   `-- main.cc
|-- image
|   |-- CMakeLists.txt
|   |-- include
|   |   `-- image_func.h
|   `-- src
|       `-- image_func.cc
`-- math
    |-- CMakeLists.txt
    |-- include
    |   `-- math_util.h
    `-- src
        `-- math_util.cc

CMakelists.txt如下。是否可以为 app1 和 app2 设置数学和图像参数?我的实际项目有许多使用多个库的应用程序。

 cmake_minimum_required(VERSION 2.8)
 add_subdirectory("./image")
 add_subdirectory("./math")
 add_subdirectory("./app1")
 add_subdirectory("./app2")

使用较新版本的 cmake(自 2.8.12 起),您可以使用target_link_libraries和相关函数来管理依赖项。通过指定 PUBLIC,包含和库也将应用于使用该库的所有目标。这将把重复减少到最低限度。

对于数学和图像,您需要指定使用相应的包含目录以及您可能需要的任何库。

math/CMakeLists.txt

add_library(math ...)
target_include_directories(math PUBLIC    include ...)
target_link_libraries(math PUBLIC ...)

图像/CMakeLists.txt

add_library(image ...)
target_include_directories(image PUBLIC include ...)
target_link_libraries(image PUBLIC ...)

app1/CMakeLists.txt

add_executabke(app1 ...)
target_link_libraries(app1 PUBLIC image math)

app2/CMakeLists.txt

add_executabke(app2 ...)
target_link_libraries(app2 PUBLIC image math)