defaulting a cached variable if not set by the user command line

My need is roughly the same as in [CMake] Can an option enforce a default, even if cache is present?.

I understand, from this thread, that cmake may relaunch a configuration by itself, without using the command line arguments but looking into the cache.

Let say, for instance, that I have an option to use -Werror warning option, lets call it WAE.

If the user don’t set value to WAE or write -DWAE=OFF, I would expect the WAE variable to be set to OFF (inside the cache).

If the user write -DWAE=ON, I would expect the WAE variable to be set to ON (inside the cache).

Is it possible to achieve this behavior? (beyond merely documenting that WAE is mandatory?)

Maybe I could unset the variable at the end of configuration/generation but how can I do that (in the scenario where cmake has to relaunch itself, the unset must not occurred until the task has successfully terminated)?

Thanks,
A.

In your project, check if WAE is defined. If it isn’t, set a regular non-cache variable WAE to whatever value you want as the default when the user doesn’t specify anything. Don’t define any WAE cache variable yourself. This way, if there is a cache variable by that name, you know the user created it.

This isn’t perfect. The main drawback is that the user has to know about WAE in order to use it. They won’t see it in the cache unless they set it themselves.

Hi,

Thanks for your answer. In order to be sure to understand well: when a variable MYVAR is set through CLI, it is equivalent to a set(MYVAR CACHE FORCE)?

Regards,
A.

That’s right.

1 Like