[CMake] Should configuration package files define module package variables?

P F pfultz2 at yahoo.com
Sat Sep 2 04:08:25 EDT 2017


> On Aug 25, 2017, at 11:21 AM, Robert Dailey <rcdailey.lists at gmail.com> wrote:
> 
> So I've been studying the find_package[1] and "creating packages"[2]
> documentation, as well as the CMakePackageConfigHelpers[3] page.
> 
> Based on the current offerings of configuration packages, I do not
> understand the need for the relocatable config.cmake file when all it
> really contains is:
> 
> include(${CMAKE_CURRENT_LIST_DIR}/foo-config.cmake)

In general, if the library does not have any dependencies, you can just export the targets directly to the config.cmake file:

install(TARGETS foo EXPORT foo-config)
install(EXPORT foo-config DESTINATION lib/cmake/foo)

However, if the library has dependencies, you will need to iterate over them in the config.cmake file. That is if `foo` uses zlib, like this:

find_package(ZLIB)
target_link_libraries(foo ZLIB::ZLIB)

Then the foo-config.cmake needs to do this(assuming the export targets are written to foo-targets):

include(CMakeFindDependencyMacro)
find_dependency(ZLIB)
include("${CMAKE_CURRENT_LIST_DIR}/foo-targets.cmake”)

The reason for this is that the imported foo target will link against ZLIB::ZLIB, but it will not define it. Actually, the generated foo-targets.cmake will create an error if ZLIB::ZLIB doesn’t exists, which is why `find_dependency(ZLIB)`(which is really just `find_package` underneath) needs to be called before including the foo-targets.cmake.

Hopefully that makes sense.

> 
> However, what I'm wondering is even though the import targets should
> contain all information about include directories, libraries, etc,
> should I still define the typical Foo_INCLUDE_DIRS, Foo_LIBRARIES
> variables? Example of what foo-config.cmake would be like:
> 
> include(${CMAKE_CURRENT_LIST_DIR}/foo-config.cmake)
> set( Foo_INCLUDE_DIRS "... path here...." )
> set( Foo_LIBRARIES "List of libraries here...” )

In general, defining relocatable variables like `Foo_INCLUDE_DIRS` was more common in with cmake 2.8. With modern cmake using just the imported targets is much better then dealing with all those variables and trying to make them relocatable.




More information about the CMake mailing list