Precedence of <PackageName>_ROOT in package search

I have a cmake file that searches for OpenSSL using find_package(OpenSSL REQUIRED), I noticed that paths that appear in CMAKE_PREFIX_PATH have precedence over the OPENSSL_ROOT_DIR i.e.

CMAKE_PREFIX_PATH="" CMAKE_LIBRARY_PATH="" cmake "-DOPENSSL_ROOT_DIR=/XXX/boringssl-build"  ..

finds the SSL library in the OPENSSL_ROOT_DIR as expected:

-- Found OpenSSL: /XXX/boringssl-build/lib/libcrypto.a (found version "3.0.8")

but

CMAKE_PREFIX_PATH="/YYY-openssl-3.0.8" CMAKE_LIBRARY_PATH="" cmake "-DOPENSSL_ROOT_DIR=/XXX/boringssl-build"  ..

finds the SSL library in the CMAKE_PREFIX_PATH:

-- Found OpenSSL: /YYY-openssl-3.0.8/lib/libcrypto.so (found version "3.0.8")

Is this a bug or expected behavior? I would expect OPENSSL_ROOT_DIR to take precedence since it’s a more specific configuration.

That is expected behavior, the OPENSSL_ROOT_DIR is documented as being a HINT which would mean it is used after CMAKE_PREFIX_PATH. What you want is OpenSSL_ROOT which is searched first.

See the bottom https://cmake.org/cmake/help/latest/command/find_library.html ( or any of the find calls ) to see the search priority rules.