'What's the effect of export CMAKE_PREFIX_PATH=...?

When google-ing export CMAKE_PREFIX_PATH, you will often find the suggestion to cure the problem that CMake doesn't find this or that package by setting an environment variable:

export CMAKE_PREFIX_PATH=/path/to/package

I've convinced myself that setting this environment variable has the effect of appending /path/to/package to the list of paths specified in the CMake call using

cmake -DCMAKE_PREFIX_PATH="/path/to/package1;..." .

(I've tried this on macOS Catalina and Ubuntu 18.04 using CMake 3.15.5 and 3.16.0, respectively.)

The documentation doesn't mention any of this. In fact, it simply states:

By default this [CMAKE_PREFIX_PATH] is empty. It is intended to be set by the project.

(see CMake documentation). There's no mention of the effect of setting the environment variable.

This raises two questions:

  • Is this effect of setting the environment variable intended? Where is it documented? Is this the canonical way of adding prefix paths to all projects build in the environment?

  • As the documentation says, "It [CMAKE_PREFIX_PATH] is intended to be set by the project". Is there any reason why there shouldn't be a way to set a default CMAKE_PREFIX_PATH?



Solution 1:[1]

The effect of setting it as an environment variable is, by default, no effect. CMake defines it's own variables (those set with the set() command, or the -D command line argument) in a file called CMakeCache.txt in the root of your CMake project. Those are the variables which will affect your cmake script.

In order to access and environment variable in CMake, you need to specify the ENV Syntax

$ENV{VAR}

Hence, even if you set a CMAKE_PREFIX_PATH environment variable, it will have no effect unless you explicitly use it in you CMakeLists.txt.

(Edit: I have only verified this behavior on Windows 10 with CMake 3.16.3)

Solution 2:[2]

Setting the CMAKE_PREFIX_PATH environment variable works in finding things with function find_file, find_path, etc.

Just because by default these functions use the CMAKE_PREFIX_PATH environment variable as a path hint as well as the CMAKE_PREFIX_PATH variable set via -DCMAKE_PREFIX_PATH=xx or set function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jrswgtr