Daniel Walton
Daniel Walton

Reputation: 113

change library dependencies in CMake build

I'm building a library that depends on other static libraries, for testing, I have to change out one of the libraries for a test version. For the life of me I can't work out how to do this with CMake.

My CMake setup is something like the following:

add_library(X STATIC x.cpp)

add_library(Y STATIC y.cpp)

add_library(A STATIC a.cpp)
target_link_libraries(A X Y)

add_executable(EXE main.cpp)
target_link_libraries(EXE A)

This works fine, but now I want to create another executable that uses TEST_X instead of X. This is a simplified example, but I have a very complex dependencies from a legacy system.

So, how do I build a new executable linked with the different library (TEST_X instead of X)?

Upvotes: 4

Views: 1587

Answers (2)

Florian
Florian

Reputation: 43020

If you set CMP0022 policy to NEW, "INTERFACE_LINK_LIBRARIES defines the link interface.". That allows you to manipulate library dependency at a later point through the INTERFACE_LINK_LIBRARIES target property.

So in your case you can remove the dependency of A to X and add the wanted library dependency directly to your executable targets:

cmake_minimum_required(VERSION 2.8)
project(ChangeLibDeps)

cmake_policy(SET CMP0022 NEW)

add_library(X STATIC x.cpp)
add_library(TEST_X STATIC test_x.cpp)

add_library(Y STATIC y.cpp)

add_library(A STATIC a.cpp)
target_link_libraries(A X Y)

get_target_property(_libs A INTERFACE_LINK_LIBRARIES)
list(REMOVE_ITEM _libs X)
set_target_properties(A PROPERTIES INTERFACE_LINK_LIBRARIES ${_libs})

add_executable(EXE main.cpp)
target_link_libraries(EXE A X)

add_executable(TEST_EXE main.cpp)
target_link_libraries(TEST_EXE A TEXT_X)

Upvotes: 2

Torbjörn
Torbjörn

Reputation: 5800

As far as I understand you correctly, you want an executable TEST_EXE depending on library A, which does not depend on library X but TEST_X, right?

I don't see any other way than creating a new library target TEST_A depending on TEST_X and not X and using this new TEST_A in a new executable TEST_EXE:

add_library(TEST_X STATIC test_x.cpp)
add_library(TEST_A STATIC a.cpp)
target_link_libraries(TEST_A TEST_X Y)
add_executable(TEST_EXE main.cpp)
target_link_libraries(TEST_EXE TEST_A)

Upvotes: 2

Related Questions