-1

Consider the following CMakeLists.txt file:

cmake_minimum_required(VERSION 3.25.0 FATAL_ERROR)
project(foo)
set(my_list one two three)
if ("two" IN_LIST ${my_list})
  message("two is in your list")
else()
  message("two is NOT in your list")
endif()

When I run this (i.e. when cmake-configuring using this file), I get:

CMake Error at CMakeLists.txt:4 (if):
  if given arguments:

    "two" "IN_LIST" "one" "two" "three"

  Unknown arguments specified

What's wrong with my script? I thought this is how IN_LIST should work....

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

1

The right parameter of IN_LIST condition is a name of the variable, which contains a list. Not a content of the list.

Correct:

set(my_list one two three)
if ("two" IN_LIST my_list)
  message("two is in your list")
else()
  message("two is NOT in your list")
endif()
Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
  • I'd figured it out before you answered by playing around with the script. Anyway, thanks. But - I wonder why the case of more arguments, with the first argument not being a variable name, is not interpreted as list to search. – einpoklum Mar 25 '23 at 15:45
  • Hmm, not sure that I understand you question. The `IN_LIST` condition consists exactly from 3 elements. So 5 elements are never correct for this condition. Or do you ask, why they **design** that kind of condition to accept only a variable name, not a content of the list? – Tsyvarev Mar 25 '23 at 15:53
  • My question is indeed about the design - why doesn't CMake accept more arguments as an "immediate" list? – einpoklum Mar 25 '23 at 16:45
  • Assume that `my_list` variable is filled by a user, and a user enters its as **4 elements**: "my_list", "AND", "FALSE". In that case, when called as `if ("two" IN_LIST ${my_list})`, the `if` command will see the following arguments: "my_list", "IN_LIST", "two" ,"AND", "FALSE", which also corresponds to **combination of two conditions**: ("two" IN_LIST "my_list") and <(result-of-IN_LIST)> AND FALSE. Which is definitely not expected by a developer. That is why every operand for every `if` condition is a **single-value**: that allows `if` command to generate correct logic for any operands values. – Tsyvarev Mar 25 '23 at 19:37
  • 1
    Probably, CMake could allow "inline lists" as a right argument of the IN_LIST command: `if ("two" IN_LIST "one;two;three")`. This is similar to specification of options in command [cmake_parse_arguments](https://cmake.org/cmake/help/latest/command/cmake_parse_arguments.html). – Tsyvarev Mar 25 '23 at 19:44
  • I hate CMake syntax T_T ... – einpoklum Mar 25 '23 at 21:31