listcmakeset-operations

How do I manipulate CMake lists as sets?


In CMake, lists are used extensively. Sometimes you have two lists of items (strings, basically), and you want to consider their intersection, difference or union. Like in this case that just came up for me.

How do I produce such intersection, difference or union lists?

Note: The outputs need to have no duplicates, the inputs not really


Solution

  • Suppose our lists are in variables S and T.

    For the union, write:

    list(APPEND union_list ${S} ${T})
    list(REMOVE_DUPLICATES union_list)
    

    For set difference, write:

    list(APPEND S_minus_T ${S})
    list(REMOVE_ITEM S_minus_T ${T})
    

    And then we use some set identities to obtain the intersection through the symmetric difference: