cmake

Map in Cmake script


I'd like to map a variable to a string, as in this example in pseudo-cmake code

map(mymap "val1" "key1" "val2" "key2") # <-- this seems not to exist
set(filename "prependfilename${mymap[${avar}]}otherpartoffilename") 

basically in my case i have to concat the strings "a32" or "a64" on the filename based on the ${ANDROID_ABI} (which is a variable expressing the target architecture type) value.

How to achieve a simple map behaviour for variables in CMake?


Solution

  • CMake doesn't support [] or {} operators, but mapping could be achieved by naming scheme for a variable:

    # The naming scheme: mymap_<key>
    set(mymap_key1 val1) # Maps key1 => val1
    set(mymap_key2 val2) # Maps key2 => val2
    # ...
    set(avar key1) # Some key
    message("Key ${avar} is mapped into: ${mymap_${avar}}")
    

    This way for "mapping" is actively used by CMake itself.

    E.g. variable CMAKE_<LANG>_COMPILER maps a programming language to the compiler and variable CMAKE_<LANG>_FLAGS_<CONFIG> maps both language and configuration type into the compiler flags, specific for this configuration.