Option and configure_file: How to be consistent?

Once again, I bare my CMake ignorance to the forum! In this case, it’s to do with option(). Namely, in some code I have, I added:

option(HYDROSTATIC "Build FV dynamics as hydrostatic" ON)
if (HYDROSTATIC)
  ...build as hydro...
else()
  ...build as non-hydro...
endif ()

And it works. Indeed, I can use -DHYDROSTATIC=NO or -DHYDROSTATIC=0 and it seems to be the same as -DHYDROSTATIC=OFF. I think this comes from CMake thinking of NO and OFF as equivalent to false and 0?

But here’s the fun thing. Later on, I want to use a configure_file() call to edit a shell script to change based on the value of HYDROSTATIC. I tried a little script:

echo "HYDROSTATIC = @HYDROSTATIC@"

and then did a:

configure_file(test.bash test.bash @ONLY)

and if I do CMake with -DHYDROSTATIC=OFF I see:

echo "HYDROSTATIC = OFF"

and if I use -DHYDROSTATIC=NO, you get:

echo "HYDROSTATIC = NO"

So, in the “real” script, I’d like to have a simple if-test:

if [[ "$HYDROSTATIC" == "OFF" ]]
then
...

rather than needing to test for every value of “false”:

if [[ "$HYDROSTATIC" == "OFF" || "$HYDROSTATIC" == "NO" || "$HYDROSTATIC" == "0" ]]
then
...

Is there some clever way of using, maybe, generator expressions that I could use so that no matter what synonym of true/false is used at CMake time, the build system can supply a single value to my configure_file()'d script?

You can introduce your own variable with a known set of values:

if(HYDROSTATIC)
  set(CFG_HYDROSTATIC ON)
else()
  set(CFG_HYDROSTATIC OFF)
endif()

and then use CFG_HYDROSTATIC in your configure_file() call.

Generator expressions cannot help with configure_file(), because they are evaluated and generate time, not configure time. If you were using file(GENEREATE) instead, you could use them:

$<BOOL:${HYDROSTATIC}>

will expand to either 0 or 1 based on CMake’s interpretation of the truthness of ${HYDROSTATIC}. But since it’s a configure-time decision, I would go with the fixed-value variable.

2 Likes

@Angew That was sort of what I was thinking of doing, but I was just hoping/wondering if there was some cool CMake-y way to do it I didn’t know about. I’m always surprised by some of the cool things CMake can do!

Thanks!