Search code examples
c++cmakebuild-process

Is it possible to link a cmake project to subprojects?


I have a C++ library project which comes with an examples folder. The examples are stand-alone, i.e. they can be compiled without the rest of the source tree as if they were real applications using the library. They use the provided FindMyLib.cmake to find the installed library in the system.

I would like to also be able to build them along with the whole library. Initially, I added them as subdirectories:

if(MYLIB_BUILD_EXAMPLES)
    add_subdirectory(examples/fooexample)
    add_subdirectory(examples/barexample)
endif()

But this is won't work, because I can't use find_package before the library is installed. I can add the default build directory to the search path, but that's not enough because the library is not built yet while cmake is running (obviously).

What can I do to solve this? Is there a way to transparently link the library to these subprojects while building it (and also "disable" the find_package, since it is bound to fail without an installation).


Solution

  • Just prepare fake FindMyLib.cmake, which links to the library using build tree, not an install one. E.g., it may set variable MyLib_LIBRARY variable to library target:

    cmake-build/FindMyLib.cmake:

    set(MyLib_LIBRARY MyLib)
    set(MyLib_INCLUDE_DIRECTORIES ${CMAKE_SOURCE_DIR}/include)
    ...
    

    Then prepend CMAKE_MODULE_PATH list with directory, contained fake script. Such a way it will be used by examples:

    if(MYLIB_BUILD_EXAMPLES)
        set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake-build ${CMAKE_MODULE_PATH})
        add_subdirectory(examples/fooexample)
        add_subdirectory(examples/barexample)
    endif()