CMakeMacroListOperations

From KitwarePublic
Revision as of 11:01, 1 March 2006 by Kmorel (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Back

Lists are an important component of most CMakeLists.txt files. Lists are built automatically from arguments to commands and macros. Thus, we often build lists in variables by calling SET with more than one variable argument. Surprisingly, there are very few CMake commands to handle lists. Here is a compilation of a few basic list manipulation commands.

CAR and CDR

Our first operations we take from lisp, a programming language built entirely around lists. Two fundamental functions of lisp are car, which returns the first element of a list, and cdr, which returns a list minus the first element. Here we give implementations of car and cdr CMake macros. Although they are not as efficient as their counterparts in lisp, they can still be surprisingly useful.

MACRO(CAR var)
  SET(${var} ${ARGV1})
ENDMACRO(CAR)

MACRO(CDR var junk)
  SET(${var} ${ARGN})
ENDMACRO(CDR)

Here is a simple example of their use.

SET(MYLIST hello world foo bar)

CAR(car ${MYLIST})
CDR(cdr ${MYLIST})
MESSAGE("car: ${car}")
MESSAGE("cdr: ${cdr}")

The output of the command above is

car: hello
cdr: world;foo;bar

Note that the CAR and CDR macros (as well as the rest of the macros in this document) take advantage of CMake's calling convention of expanding lists into arguments. If you quote the list argument, you get a very different result. If you change the previous example to

CAR(car "${MYLIST}")
CDR(cdr "${MYLIST}")
MESSAGE("car: ${car}")
MESSAGE("cdr: ${cdr}")

you get

car: hello;world;foo;bar
cdr: 

LIST_LENGTH

Here is a macro to get the length of a list.

MACRO(LIST_LENGTH var)
  SET(entries)
  FOREACH(e ${ARGN})
    SET(entries "${entries}.")
  ENDFOREACH(e)
  STRING(LENGTH ${entries} ${var})
ENDMACRO(LIST_LENGTH)

If you use the LIST_LENGTH macro as follows

SET(MYLIST hello world foo bar)

LIST_LENGTH(length ${MYLIST})
MESSAGE("length: ${length}")

you get this output:

length: 4

LIST_INDEX

Sometimes you want to get a particular entry of a list. This macro lets you grab the entry in a list (indexed from 1).

MACRO(LIST_INDEX var index)
  SET(list . ${ARGN})
  FOREACH(i RANGE 1 ${index})
    CDR(list ${list})
  ENDFOREACH(i)
  CAR(${var} ${list})
ENDMACRO(LIST_INDEX)

If you use LIST_INDEX with the following commands

SET(MYLIST hello world foo bar)

LIST_INDEX(first 1 ${MYLIST})
LIST_INDEX(second 2 ${MYLIST})
LIST_INDEX(third 3 ${MYLIST})
LIST_INDEX(fourth 4 ${MYLIST})
MESSAGE("first: ${first}")
MESSAGE("second: ${second}")
MESSAGE("third: ${third}")
MESSAGE("fourth: ${fourth}")

you get this output:

first: hello
second: world
third: foo
fourth: bar

Back



CMake: [Welcome | Site Map]