How do I get the last element of a CMake list of unknown length?

Viewed 1935

I have a list of unknown length containing strings. I want to compare the last item with the second to last item, but I can't find an easy way to retrieve these elements so I can compare them.

I tried getting the length of the list and then using (length-1) as the index I pass into the list GET function, but this doesn't seem to work.

set(my_list a b c) # I don't actually know the length of the original list
list(LENGTH my_list list_len)
list(GET my_list (list_len-1) last_item) # doesn't work

I expect to have element c saved in the last_item variable, but it remains empty. What is the right way to do this in CMake?

1 Answers

You have to use math in order to perform mathematical operations.

list(LENGTH my_list list_len)
math(EXPR list_last "${list_len} - 1")
list(GET my_list ${list_last} last_item)

Edit: It is possible to get elements from the end of a list using negative numbers, you can use -1 to get the last item of a list:

list(GET my_list -1 last_item)
Related