CMake Tutorial5 增加系统自省

一 内容
  1. 有些场景下,某些功能能否使用取决于目标平台(target platform)是否有该功能。本文主要说明如何通过 check_symbol_exists 实现对头文件中符号(功能)的检测,如果功能存在则使用该功能。
  2. CMake Tutorial4_2 测试支持 上修改,去掉test部分,在 MathFunctions/CMakeLists.txt 中增加 check_symbol_exists 的处理,如下:
## MathFunctions/CMakeLists.txt 
## --add
include(CheckSymbolExists)
# check_symbol_exists(...) in CMake to check the availability of symbols in header files.
check_symbol_exists(log "math.h" HAVE_LOG)
check_symbol_exists(exp "math.h" HAVE_EXP)
if(NOT (HAVE_LOG AND HAVE_EXP))
  unset(HAVE_LOG CACHE)
  unset(HAVE_EXP CACHE)
  # includes the math library. 
  # You do the same on the command-line like this: gcc test.c -lm 
  set(CMAKE_REQUIRED_LIBRARIES "m")
  check_symbol_exists(log "math.h" HAVE_LOG)
  check_symbol_exists(exp "math.h" HAVE_EXP)
  if(HAVE_LOG AND HAVE_EXP)
    target_link_libraries(MathFunctions PRIVATE m)
  endif()
endif()

if(HAVE_LOG AND HAVE_EXP)
  target_compile_definitions(MathFunctions
                             PRIVATE "HAVE_LOG" "HAVE_EXP")
endif()
  1. 修改mysqrt.cc
double mysqrt(double x)
{
#if defined(HAVE_LOG) && defined(HAVE_EXP)
  double result = exp(log(x) * 0.5);
  std::cout << "Computing sqrt of " << x << " to be " << result
            << " using log and exp" << std::endl;
#else
  double result = x;
#endif
  return result;
}
二 构建及测试
  1. mkdir build
  2. cd build
  3. cmake …
  4. cmake --build .
  5. ./Tutorial 9
Computing sqrt of 9 to be 3 using log and exp
USE_MYMATH
The square root of 9 is 3
三 Github
  1. 已上传 Github
四 参考
  1. cmake
  2. what-is-meaning-of-setcmake-required-libraries-m-in-cmake-tutorial
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值