How to check variables specified with -D command line option?

I’d like my users to be able to set various variable values on the command line. So the cmake ‘-D’ option does this. But how can I insure that the user has spelled the variable correctly on the command line? E.g. suppose the variable is GMT_INCLUDE_DIR; then the user could type:

cmake -D GMT_INCLUDE_DIR=/usr/local/include/gmt ..

But what if the user accidentally types:

cmake -D GMG_INCLUDE_DIRECTORY=/usr/local/include/gmt ..

How can CMakeLists.txt detect the misspelled variable name? E.g. can CMakeLists.txt get the names of all variables specified with the -D option?

First, you can check in the CMake code whether the expected variable is defined

if(DEFINED GMT_INCLUDE_DIR)
  # do something with that variable
else()
  message(FATAL_ERROR "GMT_INCLUDE_DIR must be defined")
endif()

Then, you can query the VARIABLES CMake property to get all defined variables:

get_cmake_property(all_variables VARIABLES)

but that doesn’t tell you whether they were specified with the -D option.

1 Like

Usually, you’ll see a warning when run CMake with an unused variable

cmake -S. -Bbuild -DNOT_USED_OPTION=ON

Will give you

CMake Warning:
  Manually-specified variables were not used by the project:

    NOT_USED_OPTION

Also, you’ll see same warn for misspelled variables.

HTH.

1 Like