4

I am trying to migrate a boost-build build system to cmake.

One of the features boost-build has is automatically linking dependencies of dependencies.

For example:

boost-build:

I'm building an executable app. It depends on lib2

exe app
:   [ glob *.cpp ]
    /proj/lib2//lib2
;

In turn, lib2 depends on lib1

lib lib2
:   [ glob *.cpp ]
    /proj/lib1//lib1
;

and lib1 has no dependencies

lib lib1
:    [ glob *.cpp ]
;

Both lib1 and lib2 are static libs.

boost-build will automatically add lib1.a to the linker line for app because it knows that lib2.a depends on lib1.a

cmake:

Explicitly stating both lib1 and lib2 in the target_link_libraries directive works:

lib1:

add_library(lib1 STATIC ${SOURCES})

lib2:

add_library(lib2 STATIC ${SOURCES})

app:

add_executable(app ${SOURCES})
target_link_libraries(app lib1 lib2)

As the number of libraries grows this becomes cumbersome.

target_link_libraries(app lib1 lib2 lib3 lib4 lib5 lib6 lib7 lib8 lib9 ... libN)

Questions:

  • Is there a way to specify that lib2 depends on lib1
  • Is there a way to tell app to pull in lib2 and whatever lib2 depends on?
Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213
  • you might want to take a look at: http://stackoverflow.com/questions/32756195/recursive-list-of-link-libraries-in-cmake – Tomasz Lewowski Apr 15 '16 at 14:23
  • 1
    @TomaszLewowski this one is a far better one: [setting-dependencies-between-libraries-cmake](http://stackoverflow.com/questions/7970071/setting-dependencies-between-libraries-cmake) – Steve Lorimer Apr 15 '16 at 14:28

1 Answers1

4

It's as simple as adding target_link_libraries to lib2

lib1:

add_library(lib1 STATIC ${SOURCES})

lib2:

add_library(lib2 STATIC ${SOURCES})
target_link_libraries(lib2 lib1)

app:

add_executable(app ${SOURCES})
target_link_libraries(app lib2)
Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213
  • 1
    Note that this approach also saves you from the headache of order-dependency with certain linker toolchains. `gcc`'s linker for instance is very picky about this and will refuse to link if you don't order the arguments in a flattened list of static libraries correctly. By modeling the library dependencies like here, CMake is able to figure all of that out for you. – ComicSansMS Apr 15 '16 at 14:30