[cmake-developers] if (FOO == BAR) ...

Matthew Woehlke matthew.woehlke at kitware.com
Thu Mar 21 17:56:03 EDT 2013


On 2013-03-21 16:55, David Cole wrote:
> I almost always do one of these for string compare to a CMake variable
> value:
>
>      if("${var}" STREQUAL "some string constant")
>      if("${var}" STREQUAL "${some_other_variable}")
>
> However, this is only because I am almost always certain that ${var}
> does not evaluate to the name of yet another CMake variable.
> If it did, I would get unintended results.
>
> So I wouldn't say it's necessarily a best-practice. It's "close enough"
> for many lines of code I've written, but a monkey-wrench could easily
> be thrown at it.
>
> Does forcing the if(VARIABLE usage rather than the if("string" usage
> make things work all the time? (Now I've thought about it too hard,
> and I can't remember if this works all the time or not...)
>
>      set(x "${var}")
>      if(x STREQUAL "some string constant")

I think this would be the only way to be 100% safe. Using a prefix (or 
suffix; same different) like 'x', 'x_', etc. will work in most cases 
(even better would be to use at least one non-identifier character for 
the prefix), but not if you are also trying to guard against 
intentionally malicious usage. (You'd be surprised what you can coerce 
into being part of a CMake variable name... in fact, offhand, NUL is 
about the only thing I am confident cannot be part of a CMake variable 
name...)

On a related note, can we get a policy to only allow variable names that 
are valid C[++] identifiers? :-)

-- 
Matthew




More information about the cmake-developers mailing list