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

2.9k views Asked by At

I want to use my headers and libs as common libraries for app1 and app2. My project tree are below. image/ and math/ are library directories used by app1 and app2. In this case, should I set same settings to both CmakeLists.txt under app1 and app2? Of course I know it works, but are there any smarter ways to set common libraries?

|-- 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

Roots CMakelists.txt is below. Is it possible to set math and image parameters for app1 and app2? My actual project has many applications which uses multiple libraries.

 cmake_minimum_required(VERSION 2.8)

 add_subdirectory("./image")
 add_subdirectory("./math")
 add_subdirectory("./app1")
 add_subdirectory("./app2")
1

There are 1 answers

0
Finn On

With newer versions oft CMake (since 2.8.12) you can use target_link_libraries and related functions to manage dependencies. By specifying PUBLIC the includes and libraries are also applied to all targets using the library. This will reduce duplication to a minimum.

For math and image you need to specify that the respective include directory is used and any libraries you might require.

math/CMakeLists.txt

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

image/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)