Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cmake: how to check if preprocessor is defined

I can't get cmake to test if a preprocessor has been defined or not. Eg:

cmake_minimum_required(VERSION 2.8.9)
project (cmake-test)
add_definitions(-DOS=LINUX)

if(NOT <what condition goes here?>)
    message(FATAL_ERROR "OS is not defined")
endif()

The following tests don't work:

if (NOT COMMAND OS)
if (NOT DEFINED OS)
if (NOT OS)

I can get it to work by using set() and just testing for a regular cmake variable and then defining the preprocessor macro. Eg:

set(OS LINUX)
if (OS)
    add_definitions(-DOS=${OS})
else()
    message(FATAL_ERROR "OS is not defined")
endif()

In case, you're wondering why I need to test it if the variable/preprocessor is in the same file, it's because in the final implementation these will come from an external file which is includeed in the main CMakeFile.txt Eg:

include(project_defs.txt)
if (OS)
    ....
like image 734
Mandeep Sandhu Avatar asked Jan 22 '16 01:01

Mandeep Sandhu


People also ask

What is ${} in CMake?

You access a variable by using ${} , such as ${MY_VARIABLE} . 1. CMake has the concept of scope; you can access the value of the variable after you set it as long as you are in the same scope. If you leave a function or a file in a sub directory, the variable will no longer be defined.

How do you set a variable in CMake?

Options and variables are defined on the CMake command line like this: $ cmake -DVARIABLE=value path/to/source You can set a variable after the initial `CMake` invocation to change its value. You can also undefine a variable: $ cmake -UVARIABLE path/to/source Variables are stored in the `CMake` cache.


1 Answers

This is to complete the answer by arrowd.

I also tried the COMPILE_DEFINITIONS option as mentioned above by arrowd unsuccessfully.

Following the documentation of CMake, at least for version 3.x, it turns out that when you call add_definitions() in CMake, it adds the definitions to the COMPILE_DEFINITIONS directory property.

Therefore, lets say you are defining the following as per your code:

add_definitions(-DOS=LINUX)

To retrieve the string with the definitions added into the variable "MYDEFS" you can use the following lines in CMake:

get_directory_property(MYDEFS COMPILE_DEFINITIONS)
MESSAGE( STATUS "Compile defs contain: " ${MYDEFS} )

Then you can check if in ${MYDEFS} the define you are looking for exists or not. For instance

if(MYDEFS MATCHES "^OS=" OR MYDEFS MATCHES ";OS=")
    MESSAGE( STATUS "OS defined" )
else()
    # You can define your OS here if desired
endif()
like image 172
Jorge Torres Avatar answered Sep 30 '22 08:09

Jorge Torres