Tamás Szelei
Tamás Szelei

Reputation: 23921

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).

Upvotes: 2

Views: 549

Answers (2)

piwi
piwi

Reputation: 5336

A solution could be to check, in your examples, whether the target that builds MyLib exists, and use it as a dependency if it does; invoke find_library() otherwise.

add_library(MyLib ...)

# examples/fooexample
if(NOT TARGET MyLib)
  find_library(MyLib)
endif()

add_executable(foo)

if(TARGET MyLib)
  add_dependencies(foo MyLib)
endif()

Upvotes: 1

Tsyvarev
Tsyvarev

Reputation: 65898

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()

Upvotes: 2

Related Questions