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