CMake find_package dependency on subproject

I have the following directory layout:

main_folder + static_lib1 + executable 
  • Both static_lib1 and executable have full CMakeLists so that they can be built independently.
  • The executable depends on static_lib1. It uses find_package() to search for "static_lib1".
  • The main folder contains CMakeLists, which includes both static_lib1 and "executable" via add_subdirectory to conveniently build the entire project in one go.

Everything works fine if I manually create "static_lib1" and then the "executable". But when I start CMakeLists from the main folder, I get an error because find_package cannot find library files from 'static_lib1' that have not been created yet.

How can I resolve this by keeping the CMakeLists files separate (i.e. not including the static_lib CMakeLists from the executable CMakeLists)?

+4
source share
1 answer

In the CMakeLists.txt executable you can check if you are building separately or as part of a project:

 if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR ) # stand-alone build find_package(static_lib1) else() include_directories(../static_lib1) link_directories(../static_lib1) ... target_link_libraries(executable static_lib1) endif() 
+3
source

Source: https://habr.com/ru/post/1382931/


All Articles