【问题标题】:How to use a CMake variable to choose which header file to include in a c program如何使用 CMake 变量来选择要包含在 c 程序中的头文件
【发布时间】:2020-09-25 13:04:25
【问题描述】:

是否可以使用 CMake 变量来决定将哪个头文件包含在 c 程序中。 我尝试了以下但没有成功:

header_a.h ->是包含以下代码的文件

#if (@CMAKE_VAR@ == "B")
    #include header.b
#else
    #include header.c
#endif

我还尝试了以下相同的失败结果: header_a.h

#ifdef CMAKE_VAR
#define CMAKE_VAR_SELECTION CMAKE_VAR
#endif

#if (CMAKE_VAR_SELECTION == "B")
   #include header.b
#else
   #include header.c
#endif

提前感谢您的帮助。

【问题讨论】:

  • 你是否在标题中使用configure_file 来扩展cmake 变量?
  • 你在 CMake 方面做过什么吗? C++ 编译器和 CMake 不会神奇地通信。我不知道你从哪里得到@CMAKE_VAR@ 的想法。

标签: c++ c cmake


【解决方案1】:

您可以使用 CMake 的 file(WRITE ...) 命令编写标头,使其包含正确的包含声明:

if (${CMAKE_VAR} EQUAL "B")
    file(WRITE "${CMAKE_CURRENT_SOURCE_DIR}/header_a.h"
"
#include <header.b>
"
    )
else()
    file(WRITE "${CMAKE_CURRENT_SOURCE_DIR}/myheader.hpp"
"
#include <header.c>
"
    )
endif()

【讨论】:

    【解决方案2】:

    您可以做的是为 CMake 中的 C/C++ 代码定义相应的宏。

    # your CMAKE variable
    set(CMAKE_VAR "B")
    # that would define macro constant CMAKE_VAR_B 
    add_definitions(-DCMAKE_VAR_${CMAKE_VAR})
    

    然后在代码中你可以使用你提出的

    #if defined(CMAKE_VAR_B)
        #include header.b
    #else
        #include header.c
    #endif
    

    【讨论】:

      猜你喜欢
      • 2017-02-24
      • 1970-01-01
      • 2011-03-20
      • 2013-08-19
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多