原文作者:
发布时间:
现在我们将在项目中添加一个库。这个库将包含我们自己计算数字平方根的实现。然后,可执行文件可以使用这个库来代替编译器提供的标准平方根函数。
在本教程中,我们将把这个库放到一个名为 MathFunctions
的子目录中。这个目录已经包含了一个头文件MathFunctions.h
和一个源文件mysqrt.cxx
。源文件中有一个叫做mysqrt
的函数,它提供了与编译器的sqrt
函数类似的功能。
在MathFunctions
目录下添加以下一行CMakeLists.txt
文件。
add_library(MathFunctions mysqrt.cxx)
为了使用新的库,我们将在顶层的CMakeLists.txt
文件中添加一个add_subdirectory()调用,这样库就会被构建。我们将新的库添加到可执行文件中,并将MathFunctions
添加为包含目录,这样就可以找到mqsqrt.h
头文件。顶层 CMakeLists.txt
文件的最后几行应该是这样的
# add the MathFunctions library
add_subdirectory(MathFunctions)
# add the executable
add_executable(Tutorial tutorial.cxx)
target_link_libraries(Tutorial PUBLIC MathFunctions)
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
"${PROJECT_SOURCE_DIR}/MathFunctions"
)
现在让我们把MathFunctions库变成可选的。虽然对于本教程来说,真的没有必要这样做,但对于大型项目来说,这是一种常见的情况。第一步是在顶层的 CMakeLists.txt
文件中添加一个选项。
option(USE_MYMATH "Use tutorial provided math implementation" ON)
# configure a header file to pass some of the CMake settings
# to the source code
configure_file(TutorialConfig.h.in TutorialConfig.h)
这个选项将在 cmake-gui 和 ccmake 中显示,默认值为 ON,用户可以更改。这个设置将被存储在缓存中,这样用户就不需要每次在构建目录上运行CMake时设置这个值。
下一个变化是使构建和链接MathFunctions库成为有条件的。要做到这一点, 我们将顶层 CMakeLists.txt
文件的结尾修改为如下所示。
if(USE_MYMATH)
add_subdirectory(MathFunctions)
list(APPEND EXTRA_LIBS MathFunctions)
list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/MathFunctions")
endif()
# add the executable
add_executable(Tutorial tutorial.cxx)
target_link_libraries(Tutorial PUBLIC ${EXTRA_LIBS})
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
${EXTRA_INCLUDES}
)
请注意使用变量EXTRA_LIBS
来收集任何可选的库,以便以后链接到可执行文件中。变量EXTRA_INCLUDES
也同样用于处理可选的头文件。这是在处理许多可选组件时的经典方法,我们将在下一步介绍现代的方法。
相应的对源码的修改也相当简单。首先,在 tutorial.cxx
中,如果我们需要的话,加入 MathFunctions.h
头文件。
#ifdef USE_MYMATH
# include "MathFunctions.h"
#endif
然后, 在同一个文件中, 让 USE_MYMATH
控制使用哪个平方根函数。
#ifdef USE_MYMATH
const double outputValue = mysqrt(inputValue);
#else
const double outputValue = sqrt(inputValue);
#endif
由于源代码现在需要 USE_MYMATH
, 我们可以将其添加到 TutorialConfig.h.in
中, 并加上以下一行。
#cmakedefine USE_MYMATH
练习:为什么要在 USE_MYMATH
选项之后配置 TutorialConfig.h.in
?如果我们把这两个选项倒过来, 会发生什么?
运行 cmake 可执行文件或 cmake-gui 来配置项目, 然后用您选择的构建工具来构建它。然后运行构建好的教程可执行文件。
使用 cmake 可执行文件或 cmake-gui 更新 USE_MYMATH
的值。重新构建并再次运行教程。sqrt 和 mysqrt 哪个函数的效果更好?
通过www.DeepL.com/Translator (免费版)翻译