How can I add a CMake target as a link library but leave out its transitive link libraries?

465 views Asked by At

I'm adding unit tests to a legacy C++ project which uses CMake, and I want to use link stubs to sever link library dependencies. However, when I set a target as a link library of a test set by passing its cmake target to target_link_libraries, CMake also adds all its transitive link libraries. This of course drags in all link libraries, including the ones which I want to stub out.

Does CMake provide any way to add a target as a link library while leaving out any of its transitive link libraries?

1

There are 1 answers

0
starball On

As stated by Tsyvarev in the comments, you can link to specific libraries without pulling in transitive dependencies using the $<TARGET_FILE:target> generator expression, but do note that when using target_link_libraries with files instead of target names, you'll lose the benefits of things like "inheritance" of interface properties like include directories, so you'll have to specify those yourself onto the test target.

Alternatively, if those transitive link libraries and the your stub replacements are also shared libraries, I think this something you can solve by using LD_PRELOAD. I.e. Just let those transitive link libraries be specified by CMake, and put your stub replacements in LD_PRELOAD. The environment field of test presets can help with configuring environment variables for tests.

On platforms that don't support LD_PRELOAD, such as Windows, there are usually other ways to fiddle with how dynamic libraries are found, such as the PATH environment variable, or using Windows APIs.