104

Imagine the following scenario: Project A is a shared library which has several dependencies (LibA, LibB, and LibC). Project B is an executable that has a dependency on project A, and therefore requires all of Project A's dependencies also in order to build.

Additionally, both projects are built using CMake, and Project A should not need to be installed (via the 'install' target) in order for Project B to use it, as this can become a nuisance to developers.

What is the best way to solve these dependencies using CMake? The ideal solution would be as simple as possible (though no simpler) and require minimal maintenance.

5
  • 3
    For future prosperity: cmake.org/Wiki/CMake/Tutorials/… Commented May 7, 2013 at 18:48
  • 1
    That tutorial doesn't seem to explain how to handle exporting external library dependencies. The only library linked against is one built by the project. I need to know how to tell Project B that Project A requires various external libraries and so these need to be add to the linking step of Project B.
    – Ben Farmer
    Commented Nov 22, 2017 at 8:35
  • Actually you should try Linux or Linux subsystem if you are a PC guy. The best thing with this platform is that Linux will install all dependencies for you. Or better yet, it suggests which dependencies you are missing and provides Sudo apt-get install mydependencies, how to install. Really easy.
    – Juniar
    Commented Aug 10, 2018 at 0:26
  • @Juniar, that does simplify and optimize things a lot, I agree. But makes deployment of software a nightmare. I would prefer having all in one package for my software and deploy it all together (even partially duplicating some libraries). Not to mention the maintenance problems. Each box will have a unique set of libs (to some degree).
    – OpalApps
    Commented Nov 29, 2018 at 10:17
  • @OpalApps, The dependencies might be installed on different paths and directories however you can still add these dependencies at compile time, or configure/include externals paths. They won`t be all installed on one path True, however "sudo apt-get install" does install on specific directories, just switch them around.
    – Juniar
    Commented Dec 1, 2018 at 22:39

3 Answers 3

173

Easy. Here is the example from the top of my head:

The top level CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.10)

# You can tweak some common (for all subprojects) stuff here. For example:

set(CMAKE_DISABLE_IN_SOURCE_BUILD ON)
set(CMAKE_DISABLE_SOURCE_CHANGES  ON)

if ("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}")
  message(SEND_ERROR "In-source builds are not allowed.")
endif ()

set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_COLOR_MAKEFILE   ON)

# Remove 'lib' prefix for shared libraries on Windows
if (WIN32)
  set(CMAKE_SHARED_LIBRARY_PREFIX "")
endif ()

# When done tweaking common stuff, configure the components (subprojects).
# NOTE: The order matters! The most independent ones should go first.
add_subdirectory(components/B) # B is a static library (depends on Boost)
add_subdirectory(components/C) # C is a shared library (depends on B and external XXX)
add_subdirectory(components/A) # A is a shared library (depends on C and B)

add_subdirectory(components/Executable) # Executable (depends on A and C)

CMakeLists.txt in components/B:

cmake_minimum_required(VERSION 2.8.10)

project(B C CXX)

find_package(Boost
             1.50.0
             REQUIRED)

file(GLOB CPP_FILES source/*.cpp)

include_directories(${Boost_INCLUDE_DIRS})

add_library(${PROJECT_NAME} STATIC ${CPP_FILES})

# Required on Unix OS family to be able to be linked into shared libraries.
set_target_properties(${PROJECT_NAME}
                      PROPERTIES POSITION_INDEPENDENT_CODE ON)

target_link_libraries(${PROJECT_NAME})

# Expose B's public includes (including Boost transitively) to other
# subprojects through cache variable.
set(${PROJECT_NAME}_INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/include
                                 ${Boost_INCLUDE_DIRS}
    CACHE INTERNAL "${PROJECT_NAME}: Include Directories" FORCE)

CMakeLists.txt in components/C:

cmake_minimum_required(VERSION 2.8.10)

project(C C CXX)

find_package(XXX REQUIRED)

file(GLOB CPP_FILES source/*.cpp)

add_definitions(${XXX_DEFINITIONS})

# NOTE: Boost's includes are transitively added through B_INCLUDE_DIRS.
include_directories(${B_INCLUDE_DIRS}
                    ${XXX_INCLUDE_DIRS})

add_library(${PROJECT_NAME} SHARED ${CPP_FILES})

target_link_libraries(${PROJECT_NAME} B
                                      ${XXX_LIBRARIES})

# Expose C's definitions (in this case only the ones of XXX transitively)
# to other subprojects through cache variable.
set(${PROJECT_NAME}_DEFINITIONS ${XXX_DEFINITIONS}
    CACHE INTERNAL "${PROJECT_NAME}: Definitions" FORCE)

# Expose C's public includes (including the ones of C's dependencies transitively)
# to other subprojects through cache variable.
set(${PROJECT_NAME}_INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/include
                                 ${B_INCLUDE_DIRS}
                                 ${XXX_INCLUDE_DIRS}
    CACHE INTERNAL "${PROJECT_NAME}: Include Directories" FORCE)

CMakeLists.txt in components/A:

cmake_minimum_required(VERSION 2.8.10)

project(A C CXX)

file(GLOB CPP_FILES source/*.cpp)

# XXX's definitions are transitively added through C_DEFINITIONS.
add_definitions(${C_DEFINITIONS})

# NOTE: B's and Boost's includes are transitively added through C_INCLUDE_DIRS.
include_directories(${C_INCLUDE_DIRS})

add_library(${PROJECT_NAME} SHARED ${CPP_FILES})

# You could need `${XXX_LIBRARIES}` here too, in case if the dependency 
# of A on C is not purely transitive in terms of XXX, but A explicitly requires
# some additional symbols from XXX. However, in this example, I assumed that 
# this is not the case, therefore A is only linked against B and C.
target_link_libraries(${PROJECT_NAME} B
                                      C)

# Expose A's definitions (in this case only the ones of C transitively)
# to other subprojects through cache variable.
set(${PROJECT_NAME}_DEFINITIONS ${C_DEFINITIONS}
    CACHE INTERNAL "${PROJECT_NAME}: Definitions" FORCE)

# Expose A's public includes (including the ones of A's dependencies
# transitively) to other subprojects through cache variable.
set(${PROJECT_NAME}_INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/include
                                 ${C_INCLUDE_DIRS}
    CACHE INTERNAL "${PROJECT_NAME}: Include Directories" FORCE)

CMakeLists.txt in components/Executable:

cmake_minimum_required(VERSION 2.8.10)

project(Executable C CXX)

file(GLOB CPP_FILES source/*.cpp)

add_definitions(${A_DEFINITIONS})

include_directories(${A_INCLUDE_DIRS})

add_executable(${PROJECT_NAME} ${CPP_FILES})

target_link_libraries(${PROJECT_NAME} A C)

To make it clear, here is the corresponding source tree structure:

Root of the project
├───components
│   ├───Executable
│   │   ├───resource
│   │   │   └───icons
│   │   ├───source
|   |   └───CMakeLists.txt
│   ├───A
│   │   ├───include
│   │   │   └───A
│   │   ├───source
|   |   └───CMakeLists.txt
│   ├───B
│   │   ├───include
│   │   │   └───B
│   │   ├───source
|   |   └───CMakeLists.txt
│   └───C
│       ├───include
│       │   └───C
│       ├───source
|       └───CMakeLists.txt
└───CMakeLists.txt

There are many points where this could be tweaked/customized or changed to satisfy certain needs, but this should at least get you started.

NOTE: I've successfully employed this structure in several medium-sized and large projects.

10
  • 19
    You are a F**** STAR ! you really got me out of a massive headache that lasted almost a day. Thanks so much 1 Commented Sep 18, 2015 at 16:03
  • 3
    I'm curious, would it compile if I were to invoke the Cmake from the "Executable" directory; or should I compile from the root of the project at all times? Commented Mar 15, 2016 at 12:29
  • 2
    I think it does have the small drawback that you define in each project the include directories twice (once for set(...INCLUDE_DIRS and once for include_directories()), which i find hard to maintain (always remembering to add a new include dependency in two places). You could querry them with get_property(...PROPERTY INCLUDE_DIRECTORIES).
    – pseyfert
    Commented Nov 17, 2017 at 11:59
  • 2
    This is really great, but how can the same thing be achieved when A, B and C are fully separate projects? I.e. I want to build A and export it to have its own ProjectConfig.cmake file, and then in B use find_package to find A on the system, somehow obtaining a list of all the libraries on which A depends so that they can be linked when building B.
    – Ben Farmer
    Commented Nov 22, 2017 at 8:45
  • 2
    @Ben Farmer, this is indeed more complicated topic which deserves a huge article to explain properly. I've never had enough patience to outline it here. In fact, that's what I do to manage my projects as this is actually the ultimate (professional) usage and intention of CMake. To manage all of that I have my own CMake framework which handles a lot behind the scenes. As an example, you could try building either of mine C++ Hacks or C++ Firewall toy projects. Commented Nov 22, 2017 at 23:29
21

Alexander Shukaev's got a great start, but there are a number of things that could be done better:

  1. Don't use include_directories. At the very least, use target_include_directories. However, you probably don't even need to do that if you use the imported targets.
  2. Use the imported targets. Example for Boost:

    find_package(Boost 1.56 REQUIRED COMPONENTS
                 date_time filesystem iostreams)
    add_executable(foo foo.cc)
    target_link_libraries(foo
      PRIVATE
        Boost::date_time
        Boost::filesystem
        Boost::iostreams
    )
    

    This takes care of the include directories, libraries, etc. If you used Boost in your headers in B, then instead of PRIVATE, use PUBLIC, and these dependencies would be transitively added to whatever depends on B.

  3. Don't use file globing (unless you use 3.12). Until very recently, file globbing only works during configuration time, so if you add files and build, it cannot detect the changes until you explicitly regenerate the project. However if you list the files directly, and attempt to build, it should recognize the configuration is out of date and regenerate automatically in the build step.

There's good talk here (YouTube): C++Now 2017: Daniel Pfeifer “Effective CMake"

Which covers a package manager idea that allows your root level CMake to work with find_package OR subdirectory, though, I've been trying to adopt the ideology of this and am having big problems with using find_package for everything and having a directory structure like yours.

0

This can also be done using the CMake Cache mechanism to achieve the same (i.e. sharing of project-specific variables):

set(VAR "value" CACHE INTERNAL "")

Refer to Stack Overflow question How to share variables between different CMake files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.