添加系统自省
让我们考虑向项目中添加一些代码,这些代码取决于目标平台可能不具备的特性。对于本例,我们将添加一些代码,这些代码取决于目标平台是否具有log和exp函数。当然,几乎每个平台都有这些功能,但是对于本教程,假设它们并不常见。
如果平台有log和exp,那么我们将使用它们来计算mysqrt函数中的平方根。我们首先使用MathFunctions/CMakeLists.txt中的CheckSymbolExists模块测试这些函数的可用性。在某些平台上,我们需要链接到m库。如果最初没有找到log和exp,则需要m库并重试。
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()
如果可用,请使用target_compile_definitions()将HAVE_LOG和HAVE_EXP指定为私有编译定义。
if(HAVE_LOG AND HAVE_EXP)
target_compile_definitions(MathFunctions
PRIVATE "HAVE_LOG" "HAVE_EXP")
endif()
如果log和exp在系统上可用,那么我们将使用它们来计算mysqrt函数中的平方根。将以下代码添加到MathFunctions/mysqrt.cxx中的mysqrt函数(在返回结果之前不要忘记#endif!):`
#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;
我们还需要修改mysqrt.cxx以包含cmath。
#include <cmath>
运行cmake可执行文件或cmake gui来配置项目,然后使用您选择的构建工具构建它并运行教程可执行文件。
现在哪个函数给出更好的结果,sqrt还是mysqrt?