Surprising error messages when using find_package before `project`
A user opened an issue on one of my libraries over a dependency's find_dependency(ZLIB) call failing. Their cmake looked like
cmake_minimum_required(VERSION 3.22)
find_package(libassert REQUIRED)
project(test CXX)
...
And they got the following error message
~/cxx/test/cmake-build-debug $ cmake ..
-- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
CMake Error at /usr/share/cmake-3.22/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
Call Stack (most recent call first):
/usr/share/cmake-3.22/Modules/FindPackageHandleStandardArgs.cmake:594 (_FPHSA_FAILURE_MESSAGE)
/usr/share/cmake-3.22/Modules/FindZLIB.cmake:120 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
/usr/share/cmake-3.22/Modules/CMakeFindDependencyMacro.cmake:47 (find_package)
/usr/local/lib/cmake/libdwarf/libdwarfConfig.cmake:31 (find_dependency)
/usr/share/cmake-3.22/Modules/CMakeFindDependencyMacro.cmake:47 (find_package)
/usr/local/lib/cmake/cpptrace/cpptrace-config.cmake:8 (find_dependency)
/usr/share/cmake-3.22/Modules/CMakeFindDependencyMacro.cmake:47 (find_package)
/usr/local/lib/cmake/libassert/libassert-config.cmake:6 (find_dependency)
CMakeLists.txt:3 (find_package)
-- Configuring incomplete, errors occurred!
I spent an embarrassing amount of time trying to figure out why on earth things were going wrong, chasing down every rabbit hole as to why this problem never showed up in my testing or CI from zlib1g weirdness to pkgconfig issues and eventually realized it was a simple issue of needing to call project(test CXX)
before find_package(libassert REQUIRED)
.
Why FindZLIB fails before project
surprises me. But more importantly, this is such a simple mistake to make with such a hard to track down error that I think CMake should provide a better diagnostic as to why things are going wrong.