cmake string token inclusion check

Pietro picture Pietro · Feb 16, 2015 · Viewed 18k times · Source

In cmake, how can I check if a string token is included in another string?

In my case, I would like to know if the name of the compiler contains the string "Clang" (e.g. "clang", "AppleClang", ...). All I could do so far is:

if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
...
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang")
...

I would like a more flexible approach, like checking for the presence of a substring.

This is what I could find in the documentation:

if( MATCHES regex) True if the given string or variable’s value matches the given regular expression.
if( LESS ) True if the given string or variable’s value is a valid number and less than that on the right.
if( GREATER ) True if the given string or variable’s value is a valid number and greater than that on the right.
if( EQUAL ) True if the given string or variable’s value is a valid number and equal to that on the right.
if( STRLESS ) True if the given string or variable’s value is lexicographically less than the string or variable on the right.
if( STRGREATER ) True if the given string or variable’s value is lexicographically greater than the string or variable on the right.
if( STREQUAL ) True if the given string or variable’s value is lexicographically equal to the string or variable on the right.

Answer

Fraser picture Fraser · Feb 17, 2015

if(<variable|string> MATCHES regex) will probably be what you're looking for.

In this particular case (assuming you're doing the same thing inside the block for Clang and AppleClang) then you can replace:

if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
...
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang")
...

with:

if(CMAKE_CXX_COMPILER_ID MATCHES "^(Apple)?Clang$")