cmakecmake-language

Cmake string to get key value pairs from a string list containing key values separated by colon


I have a stringlist (input):

set(MY_LIST "A:1;B:2;C:3")

I want to fetch the key values using foreach and set them as cmake constants. Something like:

foreach(ITEM ${MY_LIST})
   SET(<ITEM_A> <value_ofA>)
endforeach()

So basically i want the end result as but this should be achieved using a forloop:

SET(A "1")
SET(B "2")
SET(C "3")

How can i achieve this by using foreach to navigate each string in my list and set the key value pairs as cmake constants?


Solution

  • This is not so bad:

    cmake_minimum_required(VERSION 3.21)
    
    set(MY_LIST "A:1;B:2;C:3;D:foo:bar")
    foreach (pair IN LISTS MY_LIST)
      string(FIND "${pair}" ":" pos)
      if (pos LESS 1)
        message(WARNING "Skipping malformed pair (no var name): ${pair}")
      else ()
        string(SUBSTRING "${pair}" 0 "${pos}" var)
        math(EXPR pos "${pos} + 1")  # Skip the separator
        string(SUBSTRING "${pair}" "${pos}" -1 val)
        set("${var}" "${val}")
      endif ()
    endforeach ()
    
    message(STATUS "${A}")
    message(STATUS "${B}")
    message(STATUS "${C}")
    message(STATUS "${D}")
    

    The output is:

    $ cmake -P test.cmake
    -- 1
    -- 2
    -- 3
    -- foo:bar
    

    Might work on earlier versions, too. I keep up to date.