find_package: allow to specify value of cmake variables
I think it would be nice to be able to pass requested cmake variables to find_package
. That is, doing something like
find_package (MyLib REQUIRED REQUIRED_VARIABLES option1 ON option2 OFF var1 "a;b;c" var2 "foo")
If an installation is found with option1=OFF
or option2=ON
or var1
/var2
different from the specified values, it should be rejected.
Some context: I tried to do something like
find_package (MyLib QUIET)
if (MyLib_FOUND)
# Check if certain vars have a value that is compatible with my needs.
# If not, set MyLIB_FOUND=FALSE, to trigger code below
endif()
if (NOT MyLib_FOUND)
# Use FetchContent to build locally
endif()
The problem with this is that find_package
creates imported targets for MyLib
as soon as it finds it, so when FetchContent
would try to add the subdirectory, I would get errors because of a redefined target.
My workaround was to use ExternalProject
, but I don't like that it runs at build time (forcing me to choose between hard-coding MyLib targets specs or running a separate cmake project on the fly at config time, to config/build/install MyLib). I really want to stick with FetchContent.
Note: I tried to pass OVERRIDE_FIND_PACKAGE
to FetchContent_Declare
, hoping that it would allow to "throw away" the imported targets, but that's not what it was designed for (and in fact, it doesn't work, b/c declared targets can never be "discarded").
Note: while it's true that "if you need a different install, set MyLib_ROOT
to point to the specific installation you need", I've seen people (which may or may not be me) accidentally update an installation of a package on a production machine, because they copy/pasted a config script without changing the installation folder. Finding out why some test failed was complicated, until I added the checks on the tpl vars right after the successful find_package
call.
I looked at find_package documentation, and I don't think this is currently possible. I was wondering if this feature could be of general interest, or if it's too specific and/or too complicated to add.