考虑在我们的项目中添加一些代码,这些代码依赖于目标平台可能没有的特性。对于本例,我们将添加一些代码,这些代码取决于目标平台是否具有log和exp函数。
本节中使用的示例代码下载见1-简单开始cmake实践-CSDN博客。
练习1 -评估依赖可用性
目标
根据可用的系统依赖项更改实现。
步骤
源代码在Step7目录中提供。在这个练习中,完成TODO 1到TODO 5。
首先编辑MathFunctions/CMakeLists.txt。包括CheckCXXSourceCompiles模块。然后,使用check_cxx_source_compiles来确定log和exp是否可以从cmath中获得。如果它们可用,使用target_compile_definitions()指定HAVE_LOG和HAVE_EXP作为编译定义。
在MathFunctions/mysqrt.cxx包含cmath。然后,如果系统有log和exp,用它们来计算平方根。
操作
在这个练习中,我们将使用CheckCXXSourceCompiles模块中的函数,所以首先我们必须将它包含在MathFunctions/CMakeLists.txt中。
// TODO 1: MathFunctions/CMakeLists.txt
include(CheckCXXSourceCompiles)
然后使用check_cxx_compiles_source测试log和exp的可用性。这个函数允许我们在真正的源代码编译之前尝试编译带有所需依赖项的简单代码。结果变量HAVE_LOG和HAVE_EXP表示这些依赖项是否可用。
// TODO 2: MathFunctions/CMakeLists.txt
check_cxx_source_compiles("
#include <cmath>
int main() {
std::log(1.0);
return 0;
}
" HAVE_LOG)
check_cxx_source_compiles("
#include <cmath>
int main() {
std::exp(1.0);
return 0;
}
" HAVE_EXP)
接下来,我们需要将这些CMake变量传递给我们的源代码。这样,我们的源代码就可以知道哪些资源是可用的。如果log和exp都可用,使用target_compile_definitions()将HAVE_LOG和HAVE_EXP指定为PRIVATE编译定义。
// TODO 3: MathFunctions/CMakeLists.txt
if(HAVE_LOG AND HAVE_EXP)
target_compile_definitions(SqrtLibrary
PRIVATE "HAVE_LOG" "HAVE_EXP"
)
endif()
target_link_libraries(MathFunctions PRIVATE SqrtLibrary)
endif()
因为我们可能会使用log和exp,所以我们需要修改mysqrt。CXX包含cmath。
// TODO 4: MathFunctions/mysqrt.cxx
#include <cmath>
如果系统上有log和exp,那么在mysqrt函数中使用它们来计算平方根。MathFunctions/mysqrt中的mysqrt.cxx看起来如下:
#if defined(HAVE_LOG) && defined(HAVE_EXP)
double result = std::exp(std::log(x) * 0.5);
std::cout << "Computing sqrt of " << x << " to be " << result
<< " using log and exp" << std::endl;
#else
double result = x;
// do ten iterations
for (int i = 0; i < 10; ++i) {
if (result <= 0) {
result = 0.1;
}
double delta = x - (result * result);
result = result + 0.5 * delta / result;
std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
}
#endif
编译并运行
新建一个名为Step7_build的目录。编译并运行./Tutorial可执行文件。
mkdir Step7_build
cd Step7_build
cmake ../Step7
cmake --build .
运行可执行文件,如:
./Tutorial 100
//输出如下
Computing sqrt of 100 to be 10 using log and exp
The square root of 100 is 10