Why do I need FORCE to override a CMake option?

2019-07-05 13:45发布

问题:

I want to override an option, which formely was set to OFF. I am using

SET(USE_OPTION ON CACHE BOOL "Override option" FORCE)

Just for my curiosity: Why do I need 'FORCE' (without it, the set() does not work)

回答1:

From the docs:

If CACHE is present, then the is put in the cache instead, unless it is already in the cache

I assume the previous option was also CACHE.

If FORCE is specified, the value of the cache variable is set, even if the variable is already in the cache.

So, if you don't specify FORCE it doesn't get added to the cache as per above.



回答2:

Options are variables meant to be changeable by the user after the configuration step and before the actual build enviroment generation through tools like the cmake-gui, ccmake or through the -D command line switch.

That's why they are cached in the first place. The choice the user has done has to be persisted. So

option(USE_OPTION "My option" ON)

is an equivalent to

set(USE_OPTION ON CACHE BOOL "My option")

So to change or force an "user definable value" / cached variable you have to FORCE it.

Or hide/overwrite it for the current variable scope with a non-cached variable:

set(USE_OPTION ON)

Reference

  • What's the CMake syntax to set and use variables?


标签: cmake