Cmake check if Mac OS X, use APPLE or $ {APPLE}

I would like to check if I am on Mac OS X or not and have the following code

cmake_minimum_required (VERSION 3.0)
project (test)
set (FOO 1)
if (${FOO} AND ${APPLE})
  message ("MAC OS X")
endif ()

      

Error on a non-OSX system with an error message

CMake Error at CMakeLists.txt:4 (if):
  if given arguments:

    "1" "AND"

  Unknown arguments specified

      

If I replaced ${APPLE}

with APPLE

, the error disappeared. But I'm a little confused about this. When should we refer to the variable c ${VAR}

and when should we not?

Thanks in advance.

+3


source to share


2 answers


In short: everything inside the if brackets is evaluated as an expression, this is the semantics of the keyword if

. So if you put in APPLE

there, it gets evaluated as a variable name and gives the correct result.

Now if you put it ${APPLE}

there ${}

will evaluate its content before the if

expression evaluates. Therefore, it is the same as if you wrote

if (1 AND )

      

(in case the variable is APPLE

not set, which is the case for non-OSX systems). This is invalid syntax and gives an error. You should write:

if (FOO AND APPLE)

      

Quoting from CMake Documentation :

The if command was written very early in the history of CMakes, predates the $ {} variable evaluation syntax, and for convenience evaluates variables named by their arguments, as shown in the captions above. Note that the usual $ {} variable evaluation is applied before the if command even accepts arguments. So code like:



set(var1 OFF)
set(var2 "var1")
if(${var2})

      

the if command appears:

if(var1)

      

and is evaluated according to the if () doc above. The result is OFF, which is false. However, if we remove $ {} from the example, the command will see:

if(var2)

      

which is true because var2 is defined to be "var1", which is not a false constant.

+4


source


Not 100% relevant, but when googling for checking OSx in CMake, this is the top post. For others who land here asking the same question, it worked for me.



if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    set(MACOSX TRUE)
endif()

      

+2


source







All Articles