cmake:如何检查是否定义了预处理器 [英] cmake: how to check if preprocessor is defined

查看:120
本文介绍了cmake:如何检查是否定义了预处理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法获得 cmake 来测试是否已定义预处理器。例如:

  cmake_minimum_required(版本2.8.9)
项目(cmake测试)
add_definitions(- DOS = LINUX)

if(不是<什么条件会发生在这里?>)
消息(FATAL_ERROR未定义操作系统)
endif()

以下测试无效:

 如果(没有命令的操作系统)
如果(没有定义的操作系统)
如果(没有操作系统)

我可以使用 set()使其正常工作,而只需测试常规的 cmake 变量,然后定义预处理器宏。例如:

  set(OS LINUX)
if(OS)
add_definitions(-DOS = $ { OS})
else()
消息(FATAL_ERROR未定义操作系统)
endif()

如果您想知道为什么变量/预处理器位于 same 文件中,为什么我需要对其进行测试,这是因为在最终实现中,这些变量/预处理器会从主文件CMakeFile.txt中包含 include 的外部文件中,例如:

  include(project_defs.txt)
if(OS)
....




我也尝试了上述箭头所提到的COMPILE_DEFINITIONS选项,但未成功



至少在3.x版本的CMake文档中,发现当您调用 add_definitions(),它将定义添加到COMPILE_DEFINITIONS 目录 属性。



因此,可以说您正在根据代码定义以下内容:

  add_definitions(-DOS = LINUX)

要检索将定义添加到变量 MYDEFS中的字符串,可以使用CMake中的以下行:

  get_directory_property(MYDEFS COMPILE_DEFINITIONS)
MESSAGE(状态编译定义包含: $ {MYDEFS })

然后您可以检查是否在 $ {MYDEFS} 您要查找的定义是否存在。例如

  if(MYDEFS MATCHES ^ OS = OR MYDEFS MATCHES; OS =)
MESSAGE(状态已定义操作系统)
else()
#如果需要,您可以在此处定义操作系统
endif()


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)
    ....

解决方案

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()

这篇关于cmake:如何检查是否定义了预处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆