Issue
I am using CMake to configure some scripts required to build my project using configure_file
.
Some of these scripts do not have any math functionality, so I need to compute derived values in my CMake script using the math
macro, e.g.:
math(EXPR EXAMPLE_BLOCK_SIZE "${EXAMPLE_SIZE} / ${EXAMPLE_BLOCK_COUNT}")
However, it seems that math
does not support floating point arithmetic. If I set -DEXAMPLE_SIZE=2.5
and -DEXAMPLE_BLOCK_COUNT=2
CMake throws an error:
math cannot parse the expression: "2.5 * 2": syntax error, unexpected
exp_NUMBER, expecting $end (2)
Is there any way to compute a real number directly using CMake macros?
If not, what would be a portable way to achieve this?
Solution
First of all, floating-point math is not supported on CMake as far as I know. It is possible to compute variables, however, using shell commands. The following CMake function should do the trick:
function(floatexpr expr output)
execute_process(COMMAND awk "BEGIN {print ${expr}}" OUTPUT_VARIABLE __output)
set(${output} ${__output} PARENT_SCOPE)
endfunction()
Example usage:
set(A 2.0)
set(B 3.0)
floatexpr("${A} / ${B}" RESULT)
message(${RESULT})
NOTE: More advanced computations (such as trigonometric functions) can be computed using the command bc -l <<< 'EXPRESSION'
, but it's not part of the standard system packages and may not be installed.
EDIT: A completely portable (albeit much slower) solution would be to use the try_run
functionality to compile a C file that runs the expression:
function(floatexpr expr output)
SET(FLOAT_EXPR_SRC "
#include <stdio.h>
int main(int argc, char *argv[]){printf(\"%f\\n\", ${expr})\; return 0\;}
")
FILE(WRITE ${CMAKE_CURRENT_BINARY_DIR}/CMakeFloatExpr.c ${FLOAT_EXPR_SRC})
try_run(RESULT COMPRES ${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_BINARY_DIR}/CMakeFloatExpr.c
RUN_OUTPUT_VARIABLE __output)
set(${output} ${__output} PARENT_SCOPE)
endfunction()
Answered By - Tal Ben-Nun