在实现平方根函数时候,可以检查系统是否带有某个函数,比如log,exp。用CheckSymbolExists模块里的函数在math.h中检查,如果有就用exp(1/2)来替换原来的函数实现。具体如下:
- MathFunctions/CMakeLists.txt中内容如下,
add_library(MathFunctions mysqrt.cxx)
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()
if(HAVE_LOG AND HAVE_EXP) ? target_compile_definitions(MathFunctions ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?PRIVATE "HAVE_LOG" "HAVE_EXP") endif()
install(TARGETS MathFunctions DESTINATION lib) install(FILES MathFunctions.h DESTINATION include)
- MathFunctions/mysqrt.cxx内容如下,
#include <math.h> #include "MathFunctions.h" #include <cmath> #include <iostream>
double mysqrt(double x) { #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 ? ?return result; }
编译与执行,
?
|