list(REMOVE_ITEM) not working in cmake

Viewed 16070

Following is a part of my CMakeLists.txt file.

file(GLOB SOURCES "xyz/*.cpp")
message("${SOURCES}")
list(REMOVE_ITEM SOURCES "src1.cpp")
message("${SOURCES}")

Here in file "xyz/*.cpp" is a relative path. Content of ${SOURCES} is the same before and after REMOVE_ITEM.

Why is list(REMOVE_ITEM) not working in my case? Any help would be invaluable.

2 Answers

In addition to accepted answer you can use the following function to filter lists using regexp:

# Filter values through regex
#   filter_regex({INCLUDE | EXCLUDE} <regex> <listname> [items...])
#   Element will included into result list if
#     INCLUDE is specified and it matches with regex or
#     EXCLUDE is specified and it doesn't match with regex.
# Example:
#   filter_regex(INCLUDE "(a|c)" LISTOUT a b c d) => a c
#   filter_regex(EXCLUDE "(a|c)" LISTOUT a b c d) => b d
function(filter_regex _action _regex _listname)
    # check an action
    if("${_action}" STREQUAL "INCLUDE")
        set(has_include TRUE)
    elseif("${_action}" STREQUAL "EXCLUDE")
        set(has_include FALSE)
    else()
        message(FATAL_ERROR "Incorrect value for ACTION: ${_action}")
    endif()

    set(${_listname})
    foreach(element ${ARGN})
        string(REGEX MATCH ${_regex} result ${element})
        if(result)
            if(has_include)
                list(APPEND ${_listname} ${element})
            endif()
        else()
            if(NOT has_include)
                list(APPEND ${_listname} ${element})
            endif()
        endif()
    endforeach()

    # put result in parent scope variable
    set(${_listname} ${${_listname}} PARENT_SCOPE)
endfunction()

For example in question it could look as the following:

file(GLOB SOURCES "xyz/*.cpp")
message("${SOURCES}")
filter_regex(EXCLUDE "src1\\.cpp" SOURCES ${SOURCES})
message("${SOURCES}")

(Because regexp is used then . is replaced with \\.)

Related