Cmake: how to check if preprocessor is installed

I cannot get cmake to check if a preprocessor has been defined or not. For instance:

 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 do not work:

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

I can get it to work using set() and just testing the regular cmake variable and then defining the preprocessor macro. For instance:

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

In the case, you are wondering why I need to test it if the variable / preprocessor is in the same file, because in the final implementation they will come from an external file, which include ed in the main CMakeFile.txt For example:

 include(project_defs.txt) if (OS) .... 
+5
source share
2 answers

Usually, all definitions passed to the compiler are managed by CMake. That is, you create a CMake variable with

 option(SOMEFEATURE "Feature description" ON) 

or

 set(OS "" CACHE STRING "Select your OS") 

The user installs them through cmake -D OS=DOS or in the CMake GUI. You can then use the if() operator to conditionally add_definitions() on the compiler command line.

UPDATE:

If you really want to access preprocessor flags, the COMPILE_DEFINITIONS target property exists . You can access it this way:

 get_target_property(OUTVAR target COMPILE_DEFINITIONS) 
+1
source

This is to complete the answer with an arrow.

I also tried the COMPILE_DEFINITIONS option, as indicated above, with an unsupcessfully arrow.

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

Therefore, let's say you define the following according to your code:

 add_definitions(-DOS=LINUX) 

To get a string with definitions added to the MYDEFS variable, 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 the definition you are looking for exists in ${MYDEFS} 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() 
+1
source

Source: https://habr.com/ru/post/1241185/