cmake -D <var>:<type>=<value>

As far as I can recall, I have only passed command line arguments to cmake with cmake -D <var>=<value>. However, I just discovered that people on my team do the following cmake -D <var>:<type>=<value>. I knew that this form was possible but I didn’t realize that it was still convention for some cmake users. Are there reasons to prefer one over thew other? Is this legacy cmake usage?

If the project never defines <var> through set(... CACHE), you are effectively defining a variable that didn’t exist before. Setting the <type> determines the type that’s stored in the cache, which in turn changes how it’s presented in the Curses and Qt GUIs. It also affects the TYPE property of the cache entry, and if the project happens to be reading the TYPE property (though from my experience, most projects don’t), that could affect the outcome. (Of course, none of this matters for -P scripts.)

Basically, you can do one or the other. Including the type has some slight advantages over not including it, and is generally preferred, but not including it generally won’t hurt anything except under some very specific corner cases. (FWIW, I often don’t include it.)

1 Like

From Craig Scott’s book “Professional Cmake: A Practical Guide” chapter 5.

Basically there are 2 reasons:

Number 1:
"There is a special case for handling values initially declared without a type on the cmake command line. If the project’s CMakeLists.txt file then tries to set the same cache variable and specifies a type of FILEPATH or PATH, then if the value of that cache variable is a relative path, CMake will treat it as being relative to the directory from which cmake was invoked and automatically convert it to an absolute path. This is not particularly robust, since cmake could be invoked from any directory, not just the build directory. Therefore, developers are advised to always include a type if specifying a variable on the cmake command line for a variable that represents some kind of path. "

Number 2
“It is a good habit to always specify the type of the variable on the command line in general anyway so that it is likely to be shown in GUI applications in the most appropriate form.”