Search code examples
c++cmakecompilationcmakelists-options

What is the use of .cmake files in install function of CMakeLists.txt?


CMakeLists.txt

...
add_library( ${PROJECT_NAME} SHARED src/run_pipeline.cpp )

target_link_libraries( ${PROJECT_NAME} )
install( TARGETS ${PROJECT_NAME} DESTINATION lib )
install( FILES ${PROJECT_NAME}Config.cmake DESTINATION lib/cmake/${PROJECT_NAME} )

That ${PROJECT_NAME}Config.cmake file is:

add_library( pipeline_controller STATIC IMPORTED)

find_library( PIPELINE_CONTROLLER_LIBRARY_PATH pipeline_controller HINTS "${CMAKE_CURRENT_LIST_DIR}/install/lib/")

set_target_properties( pipeline_controller PROPERTIES IMPORTED_LOCATION "${PIPELINE_CONTROLLER_LIBRARY_PATH}")

In which cases do we require a separate .cmake file? What does .cmake provide which CMakeLists.txt doesn't? Why is it used in the above case?


Solution

  • You may find the introductory description here helpful.

    The <Package>Config.cmake files are package configuration files. They are useful for providing a minimal set of information about an installed package, so the consumer of the package can easily use it in their CMake project. As a package maintainer of a CMake-based project, you are highly encouraged (and frankly, expected) to provide such a file, as this is the most efficient way for others to integrate your library into their project.

    The consumer of your package will typically use find_package to find the installed package:

    find_package(SomePackage REQUIRED)
    

    The search procedure for find_package Config Mode will look for one of the following package configuration files to pull SomePackage into a CMake project:

    • SomePackageConfig.cmake
    • somepackage-config.cmake

    By providing one of these files (as the install command supports), you make it easy for others to use your package in their own CMake project.

    Craig Scott, a CMake co-maintainer, gave an in-depth presentation at CppCon 2019 providing a wealth of information about this topic.