CMake增加系统自检

有些代码可能依赖于目标平台,比如CalculateSqrt如果不用.cpp而是用.c,windows平台下编译链接没有问题,但是linux中会报错:

main.c:(.text+0x4d): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

linux并不能识别“sqrt”函数。
这就用到上上个帖子添加库中拓展内容CheckSymbolExists进行自检。
CheckSymbolExists内容:

    check_symbol_exists(<symbol> <files> <variable>)

  Check that the ``<symbol>`` is available after including given header
  ``<files>`` and store the result in a ``<variable>``.  Specify the list
  of files in one argument as a semicolon-separated list.
  ``<variable>`` will be created as an internal cache variable.

check_symbol_exists会在给定的头文件中检查函数是否可用,并且将检查结果存放在内部的缓冲变量内。
用到CalculateSqrt中就可以这样修改CMakeLists.txt

# 包含CheckSymbolExists,将结果存到HAVE_SQRT变量中
include(CheckSymbolExists)
check_symbol_exists(sqrt "math.h" HAVE_SQRT)

if(HAVE_SQRT)
   target_compile_definitions(CalculateSqrt PRIVATE HAVE_SQRT)
endif()

#如果没找到,则使用MathFunctions库
if(NOT HAVE_SQRT)
   add_subdirectory(MathFunctions)
   list(APPEND EXTRA_LIBS MathFunctions)
endif()

在执行“cmake …”时会寻找sqrt,我们可以看到没有找到sqrt。
在这里插入图片描述

当然,在实际中没有找到,也不需要自己设计sqrt,可以链接m库(math.h通常位于/lib目录下,而linux平台则是libm.so库文件)。代码如下:

if (NOT HAVE_SQRT)
	#清空HAVE_SQRT
	unset(HAVE_SQRT CACHE)
	#设置需要m库
	set(CMAKE_REQUIRED_LIBRARIES "m")
	#再次检测
	check_symbol_exists(sqrt "math.h" HAVE_SQRT)
	if(HAVE_SQRT)
		#链接m库
		target_link_libraries(CalculateSqrt PRIVATE m)
	endif()
endif()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值