Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing values in CMake lists

Tags:

cmake

I needed to replace a value in a CMake list, however there does not seem to be any support for this list operation.

I've come up with this code:

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})

Do you have any better idea how to achieve that?

like image 687
Přemysl J. Avatar asked Jul 22 '10 10:07

Přemysl J.


2 Answers

If you want to replace an item by value in the list, you can do like the following code:

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()

Example:

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}")
like image 67
Amir Saniyan Avatar answered Sep 22 '22 07:09

Amir Saniyan


You don't need the if check:

project(test)
cmake_minimum_required(VERSION 2.8)

macro(LIST_REPLACE LIST INDEX NEWVALUE)
    list(INSERT ${LIST} ${INDEX} ${NEWVALUE})
    MATH(EXPR __INDEX "${INDEX} + 1")
    list (REMOVE_AT ${LIST} ${__INDEX})
endmacro(LIST_REPLACE)

set(my_list A B C)
LIST_REPLACE(my_list 0 "FIRST")
LIST_REPLACE(my_list 1 "SECOND")
LIST_REPLACE(my_list 2 "THIRD")
message (STATUS "NEW LIST: ${my_list}")
like image 22
the_void Avatar answered Sep 22 '22 07:09

the_void