user454083
user454083

Reputation: 1397

CMake set function

I am trying to learn CMake from a tutorial. I am not crystal clear about how this set function works.

set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)

According to CMake document:

set(<variable> <value> [[CACHE <type> <docstring> [FORCE]] | PARENT_SCOPE])

If in this specific case Variable is EXTRA_LIBS, Value is ${EXTRA_LIBS}, then CACHE is MathFunctions?

Correct?

Upvotes: 2

Views: 7419

Answers (1)

ComicSansMS
ComicSansMS

Reputation: 54737

What the command is trying to do is to append the string MathFunctions to whatever value is already stored in the variable EXTRA_LIBS.

To break it down:

set(VARNAME VALUE)

sets the variable VARNAME to the string VALUE. Note that you can assign multiple values to a single variable, which will effectively assign a list value to the variable:

set(VARNAME VALUE1 VALUE2 VALUE3)

To access the value of that variable later, you have to dereference it using ${}, as in

 message(${VARNAME})

If the value assigned is a list, you might want to access the different elements separately instead:

 foreach(element ${VARNAME})
      message(${element})
 endforeach()

The command from your question does both the dereferencing of the old value and the assignment of the new value in one line.

A more descriptive way of performing the same assignment is offered by the list command:

list(APPEND EXTRA_LIBS MathFunctions)

On a related note: Note that there is a subtle difference between appending to a list and string concatenation:

set (EXTRA_LIBS "${EXTRA_LIBS} MathFunctions")

Instead of appending, this command will assign a new singular string value to the variable, that is equal to the concatenation of the previous values with the string MathFunctions.

Upvotes: 6

Related Questions