cmake学习笔记(五)
添加系统检测
检测代码环境中是否存在某些库文件,在MathFunctions/CMakeLisits.txt添加如下代码:
include(CheckSymbolExists)
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)
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()
如果代码环境中有log和exp,我们将使用他们来计算mysqrt函数中的平方根,使用
check_symbol_exists来检测这些函数的可用性,如果没有这些函数,则检测m库是否含有log和exp,有则链接到m库。
在MathFunctions/CMakelists.txt添加如下代码:
if(HAVE_LOG AND HAVE_EXP)
target_compile_definitions(MathFunctions
PRIVATE "HAVE_LOG" "HAVE_EXP")
endif()
如果可用,使用target_compile_definitions()将HAVE_LOG和HAVE_EXP指定为私有编译定义。
将如下代码添加到MathFunctions/mysqrt.cxx文件中:
#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
使mysqrt.cxx包含头文件cmath:
#include <cmath>
运行可执行文件。