我想将 header 和库用作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)

关于c++ - 如何通过cmake共享子目录中的头文件和库?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30829373/

10-09 07:13
查看更多