Variable Scope in `FooConfig.cmake` files
This is a repost from the CMake slack channel, as I got no feedback there.
Is it still recommended to use @PACKAGE_INIT@
in FooConfig.cmake.in
files? I am running into a problem with transitive dependencies, when I have a find_package
in the Config file and both projects use @PACKAGE_INIT@
. (I know find_dependency is to be preferred, but somehow that caused more problems).`
Non expanded `XXXConfig.cmake.in files:
I've got something like this:
@PACKAGE_INIT@
find_package(bar)
include("@PACKAGE_foo_install_cmake_dir@/fooTargets.cmake")
and bar does the same:
@PACKAGE_INIT@
include ("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake")
Configured files:
Now the configured config files look like this: barConfig.cmake
get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE)
#...
include ("${CMAKE_CURRENT_LIST_DIR}/barTargets.cmake")
and fooConfig.cmake
get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE)
#...
find_package(bar)
include("${PACKAGE_PREFIX_DIR}/lib/cmake/foo/fooTargets.cmake")
The actual problem now:
Anybody who now does find_package(foo)
will get an error, trying to locate /lib/cmake/foo/fooTargets.cmake
in the bar install directory.
I am assuming the way that find_package
works, the PACKAGE_PREFIX_DIR
is overwritten in barConfig.cmake
but stays in scope inside fooConfig.cmake
.
Is this a CMake bug?
There are a few workarounds: Reference files instead from CMAKE_CURRENT_LIST_DIR
. Move find_package(bar)
to the bottom of the file. But still, in theory, I would expect that to work.