How can I check in CMake whether a list contains a specific entry?

StackOverflow https://stackoverflow.com/questions/23323147

  •  10-07-2023
  •  | 
  •  

سؤال

I want to check whether a lists contains a specific entry like in the following code snippet:

macro(foo)
if ($(ARGN} contains "bar")
  ...
endif
endmacro()

CMake does not offer a contains. What is best / easiest way to get the desired result?

In CMake's wiki, I found a LIST_CONTAINS macro, but the wiki page is outdated. Is this still the best way to go, or has CMake gained new capabilities?

هل كانت مفيدة؟

المحلول

With CMake 3.3 or later, the if command supports an IN_LIST operator, e.g.:

if ("bar" IN_LIST _list)
 ...
endif()

For older versions of CMake, you can use the built-in list(FIND) function:

list (FIND _list "bar" _index)
if (${_index} GREATER -1)
  ...
endif()

نصائح أخرى

Fewer lines:

if (";${ARGN};" MATCHES ";bar;")
  #  ...
endif()

But see the IN_LIST syntax from @sakra for a more-modern syntax.

I have been using one liner like if ("${PLATFORM}" MATCHES "^(os|ios|android|linux|win32)$") to check if PLATFORM is in the list

If the intention here is to add a value to a list but only if it's not already in the list, then an alternative approach is to just add it to the list and immediately remove possible duplicates again:

list(APPEND            SOME_LIST "value")
list(REMOVE_DUPLICATES SOME_LIST)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top