有些代码可能依赖于目标平台,比如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()