Option 1: Exact match
I want to check whether that string is an integral number - possibly with whitespace.
If this is the exact spec I need, then I would check it like so:
string(STRIP "${MYVAR}" MYVAR_PARSED)
if (NOT MYVAR_PARSED MATCHES "^[0-9]+$")
message(FATAL_ERROR "Expected number, got '${MYVAR}'")
endif ()
This first removes whitespace from MYVAR
, storing the result in MYVAR_PARSED
. Then, it checks that MYVAR_PARSED
is a non-empty sequence of digits and errors out if it is not.
I think doing this ad-hoc is fine, but if you want a function:
function(ensure_int VAR VALUE)
string(STRIP "${VALUE}" parsed)
if (NOT parsed MATCHES "^[0-9]+$")
message(FATAL_ERROR "Expected number, got '${VALUE}'")
endif()
set(${VAR} "${parsed}" PARENT_SCOPE)
endfunction()
ensure_int(MYVAR_PARSED "${MYVAR}")
Option 2: Looser match
However, the following solution might in some cases be more robust, depending on your requirements:
math(EXPR MYVAR_PARSED "${MYVAR}")
This will interpret the value of MYVAR
as a simple mathematical expression over 64-bit signed C integers. It will interpret 0x
-prefixed numbers in hex. It recognizes most C arithmetic operators.
On the other hand, it might be too permissive: this solution will accept things like 0 + 0x3
. It will also variously warn or error depending on how broken the expression is. However, this might not be an issue if you subsequently validate the range of the number or something. You could, for instance, check if (MYVAR_PARSED LESS_EQUAL 0)
and then error out if so.
Documentation for the math
command: https://cmake.org/cmake/help/latest/command/math.html