set a cmake variable if it is not changed by the u

2019-01-29 02:53发布

问题:

How can i (re)set cmake variable only when it is not changed by the user?

I have this variables:

set(DIR "testdir" CACHE PATH "main directory")
set(SUBDIR ${DIR}/subdir CACHE PATH "subdirectory")

On the first run the variables are initialized to testdir and testdir/subdir.

When the user changed DIR and reruns cmake without changing SUBDIR, i would like to generate a new SUBDIR path, while i want to keep the SUBDIR path, when the user changed it.

So SUBDIR should be set to the new default value based on the new value of DIR, if DIR was changed and SUBDIR was never changed before.

回答1:

Along with cache variable SUBDIR visible to the user, you may store another cache variable, say SUBDIR_old, which contains the last value of SUBDIR and marked as INTERNAL (that is not intended to be modified by the user).

Next launching of cmake you may compare values of SUBDIR and SUBDIR_old, and if they differ, then user has modified SUBDIR:

if(NOT DEFINED SUBDIR_old OR (SUBDIR EQUAL SUBDIR_old))
    # User haven't changed SUBDIR since previous configuration. Rewrite it.
    set(SUBDIR <new-value> CACHE PATH "<documentation>" FORCE)
endif()
# Store current value in the "shadow" variable unconditionally.
set(SUBDIR_old ${SUBDIR} CACHE INTERNAL "Copy of SUBDIR")

Problem with that approach that user cannot say:

I have checked value of SUBDIR and found it already correct.

Without modification we assume that user don't bother about variable's value.



回答2:

Turning my comment into an answer

You could use MODIFIED cache variable property, but the documentation says

Do not set or get.

Maybe a better approach would be to check the modification with if statements:

set(DIR "testdir" CACHE PATH "main directory")
if (NOT DEFINED SUBDIR OR SUBDIR MATCHES "/subdir$")
    set(SUBDIR "${DIR}/subdir" CACHE PATH "subdirectory" FORCE)
endif()

Or you just don't put DIR inside SUBDIR and put the details into the description:

set(SUBDIR "subdir" CACHE PATH "subdirectory of main directory (see DIR)")


标签: cmake