
CMake教程05-添加系统自查功能
cmake提供了一些自查功能,比如检查当前系统平台是否定义了某些功能函数。
本节以log
和exp
两个函数计算平方根mysqrt
函数为例介绍如何进行系统自查。
如果系统中没有找到log
和exp
,连接到m
库再重新检测。
首先使用CheckSymbolExists
模块,具体修改func/CMakeLists.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()
if(HAVE_LOG AND HAVE_EXP)
target_compile_definitions(myfunc PRIVATE "HAVE_LOG" "HAVE_EXP")
endif()
如果可用,使用target_compile_definitions()
指定 HAVE_LOG
和HAVE_EXP
作为PRIVATE
编译宏定义。
这样,我们就可以在代码中使用HAVE_LOG
和HAVE_EXP
这两个宏来实现代码了,具体的func/myfunc.cpp
实现的mysqrt
函数如下:
double mysqrt(double x)
{
if(x <= 0) return 0;
double result = 0.0, temp = 0;
#if defined(HAVE_LOG) && defined(HAVE_EXP)
result = exp(log(x) * 0.5);
cout << "using log and exp for mysqrt of "<< x << " is " << result <<endl;
#else
result = x / 2;
temp = 0;
// It will stop only when temp is the square of our number
while(abs(result - temp) > 1e-9){
// setting sqrt as temp to save the value for modifications
temp = result;
// main logic for square root of any number (Non Negative)
result = ( x/temp + temp) / 2;
}
cout << "no log and exp for mysqrt of "<< number << " is " << result <<endl;
#endif
return result;
}
当然,这个仅仅是一个简单示例,当你有更复杂的需求时,你可以回来看看这个简单示例,可能对你有帮助。
如果我们不想使用系统的log
和exp
计算平方根,而使用自定义的计算方法,我们要怎么做呢?
转载本文时请注明出处及本文链接地址CMake教程05-添加系统自查功能。