<PackageName>_ROOT vs <Package>_DIR


Probably a duplicate, but what is the difference between these two environment variables (regarding find_package behavior). I’m failling to understand from the documentation.


The difference is in the order they are searched. According to the docs, PackageName_ROOT is used first. If it doesn’t exist/work, some CMake cache variables are tried next (CMAKE_PREFIX_PATH and some macOS-specific ones). If these don’t exist/work either, their environment variable equivalents are tried, along with PackageName_DIR.

PackageName_ROOT was also introduced in CMake version 3.12, while PackageName_DIR works in CMake older than that too.

Actually, I think the docs are wrong. If PackageName_DIR is set, and there is a package file in that location, that will be used and no search will be performed at all. I’ll need to go through the code again more carefully to be sure, but the docs listing PackageName_DIR in step 3 of the search procedure looks to be an error.

I misread the post and responses as being about cache variables, not environment variables. @Angew’s answer is correct, at least about the search order.

There is one crucial difference between the <PackageName>_ROOT and <PackageName>_DIR variables (environment or cache). The ..._ROOT variables are maintained as a stack while resolving find_package() calls. When there are nested calls, this allows the nested calls to see the parent locations as part of their search paths, so if the nested dependency is installed to the same place as the parent, it will be found. See policy CMP0074 for details, which controls this “search stack” behavior. This does not occur with the ..._DIR variables.