cmake command line -D and using DEFINED

I would like to be able to just define a cmake variable without giving it a value, similar to how the C preprocessor can define variables and check if the variable is defined.

  1. It seems that I have to use -D variable_name=
    instead of just -D variable_name ?

  2. It also seems that If I only check if the variable is defined, cmake-3.17.2
    posts a warning that the variable was not used while cmake-3.18.4 does
    not post the warning ?

CMake variables do not have such a state. They either have a value or are undefined. The value can be empty (which might be what you’re looking for). -Dvariable_name= will set it to the empty string.

CMake differences

3.18 might consider the variable “used” in an if (DEFINED) check. I’m not sure what would have changed that.

Here is my test script that gives a warning with 3.17.2 and not 3.18.4. Note that it builds in place so use a temporary directory for the test.

#! /bin/bash -e
cat << EOF > CMakeLists.txt
PROJECT(cmake_defined)
IF( DEFINED variable )
    MESSAGE(STATUS "variable is defined")
ELSE( DEFINED variable )
    MESSAGE(STATUS "variable is not defined")
ENDIF( DEFINED variable )
EOF
cmake -D variable= .

I’m not sure this is a regression (we don’t guarantee when warnings fire), but thanks for the test case.

Cc: @kyle.edwards @brad.king

The command-line syntax for adding a cache entry is -DVAR=$value for some $value, which may or may not be empty. I don’t think we define behavior for plain -DVAR.

my test script that gives a warning with 3.17.2 and not 3.18.4

That script gives me a “Manually-specified variables were not used by the project” warning with 3.17.5, 3.18.5, and 3.19.1. Be sure to use a fresh tree each time because once the variable is in CMakeCache.txt the warning won’t appear again.

My mistake. I corrected my test case and got the warning in 3.18.4.

#! /bin/bash -e
if [ -e CMakeCache.txt ]
then
    rm CMakeCache.txt
fi
cat << EOF > CMakeLists.txt
PROJECT(cmake_defined)
IF( DEFINED variable )
    MESSAGE(STATUS "variable is defined")
ELSE( DEFINED variable )
    MESSAGE(STATUS "variable is not defined")
ENDIF( DEFINED variable )
EOF
cmake -D variable= .

Thanks

The command line interface explicitly considers -DVAR an error.