Search code examples
cmakecmake-language

What's the point of using empty string to set cache variable in CMake?


I've seen different ways of setting / using Cache variables in Cmake. What is the standard?

What's the point of setting an empty string ("") to the cache variable?

Example

set(NVTX_ROOT_DIR "" CACHE PATH "Folder contains NVIDIA NVTX")

Solution

  • What's the point of setting an empty string ("") to the cache variable?

    It is not just setting a value for a CACHE variable.

    Command flow set(CACHE) normally performs two things:

    1. Declares the parameter (assigns description and possibly the type)
    2. Sets the parameter's default value. (That is, if the parameter is already set, its value isn't changed).

    Empty value for CACHE variable could mean that a parameter denoted by this variable is not set. Depending on the project which uses it, this could be interpreted as:

    • Do not use functionality described by the parameter.
    • Emit an error telling the parameter should be set by a user.

    In CMake code checking the parameter could be implemented with simple if(VAR):

    if(NVTX_ROOT_DIR)
      # The parameter is set
    else()
      # The parameter is not set
    endif()
    

    While if(NVTX_ROOT_DIR) is false even if the variable is not set, declaring the parameter is impossible without setting its value. So empty string as a default value is a logical choice for being able to use simple if(NVTX_ROOT_DIR) for check absence of the parameter's setting.