[CMake] Duplicating a shared library and replacing target link libraries

Rainer Poisel rainer.poisel at gmail.com
Sun Dec 4 15:01:09 EST 2016


Hello,

I am currently developing a test-framework that offers two versions of
a base-library:
  * the "originalLibrary" and
  * a library "originalLibraryForward" that has the same interface as
the "originalLibrary". Calls to "originalLibraryForward"-functions can
be forwarded to the "originalLibrary", however it is also possible to
install pre- and post-call hooks, implement different behavior,
reference counting, etc.

Other libraries linking against "originalLibrary" can be tested by
linking against "originalLibraryForward". In my build environment I
want to have both versions of a library: one linking against
"originalLibrary" and one linking against "originalLibraryForward".

In order to minimize the effort to create the library linking against
"originalLibraryForward", I wrote a function that "recreates" the
library, however the linker is instructed to link against
"originalLibraryForward" instead of "originalLibrary":

8<======================
function(AddMockedLibrary libraryName)
    get_target_property(sourceFiles ${libraryName} SOURCES)
    get_target_property(linkLibs ${libraryName} LINK_LIBRARIES)
    get_target_property(includeDirs ${libraryName} INCLUDE_DIRECTORIES)
    get_target_property(compileDefinitions ${libraryName} COMPILE_DEFINITIONS)
    get_target_property(compileOptions ${libraryName} COMPILE_OPTIONS)

    add_library(${libraryName}_MOCK SHARED
        ${sourceFiles}
    )

    target_include_directories(${libraryName}_MOCK PRIVATE
        ${includeDirs}
    )

    list(REMOVE_ITEM linkLibs
        originalLibrary
    )
    target_link_libraries(${libraryName}_MOCK PRIVATE
        ${linkLibs}
        originalLibraryForward
    )

    if (compileOptions)
        target_compile_options(${libraryName}_MOCK PRIVATE
            ${compileOptions}
        )
    endif()

    if (compileDefinitions)
        target_compile_definitions(${libraryName}_MOCK PRIVATE
            ${compileDefinitions}
        )
    endif()
endfunction()
8<======================

Now to my problems: this approach works fairly well with two exceptions:

The library linking against "originalLibraryForward" has to be
compiled from the original sources too. Actually performing the
linking step should be sufficient. Is there a way to accomplish that?

The function does not work when the library passed to
AddMockedLibrary() uses target_link_libraries() with IMPORTED targets
from, e. g. calls to find_package(). In order to make creating the
_MOCK-Library work I have to duplicate the original call to
find_package() before calling AddMockedLibrary(). Is there a way to
automate this as well?

Thanks for your help,
  Rainer


More information about the CMake mailing list