我需要替换CMake列表中的值,但似乎没有任何支持此列表操作。
我想出了这段代码:
macro (LIST_REPLACE LIST INDEX NEWVALUE)
list (REMOVE_AT ${LIST} ${INDEX})
list (LENGTH ${LIST} __length)
# Cannot insert at the end
if (${__length} EQUAL ${INDEX})
list (APPEND ${LIST} ${NEWVALUE})
else (${__length} EQUAL ${INDEX})
list (INSERT ${LIST} ${INDEX} ${NEWVALUE})
endif (${__length} EQUAL ${INDEX})
endmacro (LIST_REPLACE)
# Example
set (fubar A;B;C)
LIST_REPLACE (fubar 2 "X")
message (STATUS ${fubar})
你有更好的想法如何实现这个目标吗?
答案 0 :(得分:13)
答案 1 :(得分:0)
如果要用列表中的值替换项目,可以执行以下代码:
macro(replace_list_item LIST OLD_VALUE NEW_VALUE)
list(FIND ${LIST} ${OLD_VALUE} OLD_VALUE_INDEX)
if(OLD_VALUE_INDEX GREATER_EQUAL 0)
list(REMOVE_AT ${LIST} ${OLD_VALUE_INDEX})
list(INSERT ${LIST} ${OLD_VALUE_INDEX} ${NEW_VALUE})
endif()
endmacro()
示例:
set(OPENCV_OPTIONS "")
list(APPEND OPENCV_OPTIONS -D WITH_ADE=ON)
list(APPEND OPENCV_OPTIONS -D WITH_CUDA=OFF)
list(APPEND OPENCV_OPTIONS -D WITH_EIGEN=ON)
# Old OPENCV_OPTIONS: -D;WITH_ADE=ON;-D;WITH_CUDA=OFF;-D;WITH_EIGEN=ON
message("Old OPENCV_OPTIONS: ${OPENCV_OPTIONS}")
replace_list_item(OPENCV_OPTIONS "WITH_CUDA=OFF" "WITH_CUDA=ON")
# New OPENCV_OPTIONS: -D;WITH_ADE=ON;-D;WITH_CUDA=ON;-D;WITH_EIGEN=ON
message("New OPENCV_OPTIONS: ${OPENCV_OPTIONS}")