'Ignoring CMake cached variable

How can I force CMake to ignore cached value? I want to require the caller to pass variable each time, for example

cmake .. -DSOME_VAR=value

and if I call CMake like

cmake ..

without SOME_VAR I want that this piece of CMake code to fail:

if (NOT DEFINED)
    message(FATAL_ERROR " SOME_VAR is missing.")
endif()

It seems that unset(SOME_VAR CACHE) doesn't do what I expect. I actually don't care for cached variables at all, I don't mind if it slower.



Solution 1:[1]

You can achieve that by testing for the SOME_VAR before the project statement, i.e. your root CMakeLists.txt should contain a piece of code like this:

#very first lines of a CMakeLists.txt
#note: the test must be done **BEFORE** project statement

if(NOT SOME_VAR)
    message(FATAL_ERROR "SOME_VAR must be defined in command line")
endif()

project(project_requiring_some_var_in_cmd_line)

#the rest of your CMakeLists.txt 

Also, as already pointed out, note that this is not the natural way of using CMake. It may be beneficial if you explained the problem you are trying to solve.

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