## MathFunctions/CMakeLists.txt
## --add
include(CheckSymbolExists)#check_symbol_exists(...) in CMake to check the availability of symbols in header files.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)#includesthe math library.#You do the same on the command-line like this: gcc test.c -lm 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()
修改mysqrt.cc
doublemysqrt(double x){#ifdefined(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;#elsedouble result = x;#endifreturn result;}
二 构建及测试
mkdir build
cd build
cmake …
cmake --build .
./Tutorial 9
Computing sqrt of 9 to be 3using log and exp
USE_MYMATH
The square root of 9 is 3