这一篇博客我们将在上一篇的项目中添加一个库,库中有计算平方根的函数,这样在执行的时候就可以使调用这个库而不是编译器提供的标准平方根函数。
1、子目录建立
我们将放到子目录MathFunctions中,并且添加CMakeLists.txt文件,代码如下:
add_library(MathFunctions mysqrt.cxx)
add_library()是添加库的命令,在之前已经讲过。
2、顶层CMakeLists.txt修改
源文件mysqrt.cxx有一个名为mysqrt的函数,它提供了与编译器的sqrt函数类似的功能。为了使用这个库我们需要在顶层CMakeLists.txt文件中添加一个add_subdirectory 是调用,只有这样库才会建立。我们还需要添加include路径以便找到函数原型的MathFunctions/MathFunctions.h头文件。最后,需要将新库添加到可执行文件中。顶层CMakeLists.txt文件最后几行的代码如下:
include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
add_subdirectory (MathFunctions)
# add the executable
add_executable (Tutorial tutorial.cxx)
target_link_libraries (Tutorial MathFunctions)