如果用户未更改,则设置 cmake 变量

all*_*llo 7 cmake

仅当用户未更改 cmake 变量时,如何(重新)设置它?

我有这个变量:

set(DIR "testdir" CACHE PATH "main directory")
set(SUBDIR ${DIR}/subdir CACHE PATH "subdirectory")
Run Code Online (Sandbox Code Playgroud)

第一次运行时,变量被初始化为testdirtestdir/subdir

当用户更改DIR并重新运行 cmake 而不更改时SUBDIR,我想生成一个新路径,而当用户更改它时SUBDIR我想保留该路径。SUBDIR

因此,如果已更改并且以前从未更改过,SUBDIR则应根据 的新值设置为新的默认值。DIRDIRSUBDIR

Flo*_*ian 5

将我的评论变成答案

您可以使用MODIFIED缓存变量属性,但文档说

不要设置或获取。

也许更好的方法是使用 if 语句检查修改:

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

或者您只是不将详细信息DIR放入SUBDIR描述中:

set(SUBDIR "subdir" CACHE PATH "subdirectory of main directory (see DIR)")
Run Code Online (Sandbox Code Playgroud)


Tsy*_*rev 2

除了SUBDIR用户可见的缓存变量之外,您还可以存储另一个缓存变量,例如SUBDIR_old,它包含 的最后一个值SUBDIR并标记为 INTERNAL (用户不应修改)。

下次启动时,cmake您可以比较SUBDIR和的值SUBDIR_old,如果它们不同,则用户已修改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")
Run Code Online (Sandbox Code Playgroud)

用户不能说这种方法的问题:

我检查了 的值SUBDIR并发现它已经正确

如果不进行修改,我们假设用户不关心变量的值。