添加库
现在我们将为我们的项目中添加一个库。这个库将包含我们自己的实现,用于计算数字平方根。然后,可执行文件可使用此库而不是编译器提供的标准平方根函数。在本教程中,我们将把库放入一个名为MathFunctions的子目录。它将包含以下一行CMakeLists.txt文件:
add_library(MathFunctions mysqrt.cxx)
源文件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)
现在让我们考虑一下如何使MathFunctions库成为可选项。在本教程中没有任何理由这样做,但是使用大型库或依赖于第三方库代码时您可能会有这个想法。第一步是在顶级CMakeLists.txt文件中添加一个选项。
# should we use our own math functions?
option (USE_MYMATH "Use tutorial provided math implementation" ON)
这将显示在CMake GUI中,默认值为ON,用户可以根据需要更改。此设置将存储在缓存中,这样用户在此项目上运行CMake时都不需要继续设置它。下一个更改是使MathFunctions库的构建和链接成为条件。为此,我们将顶级CMakeLists.txt文件的末尾更改为如下所示:
# add the MathFunctions library?
#
if (USE_MYMATH)
include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
add_subdirectory (MathFunctions)
set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
endif (USE_MYMATH)
# add the executable
add_executable (Tutorial tutorial.cxx)
target_link_libraries (Tutorial ${EXTRA_LIBS})
通过使用USE_MYMATH设置来确定是否编译和使用MathFunctions。请注意,使用变量(在本例中为EXTRA_LIBS)来收集任何可选的库,以便以后链接到可执行文件中。这是用于保持具有许多可选组件的大项目组件简洁的常用方法。源代码的相应更改非常简单,我们可以看一下
// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "TutorialConfig.h"
#ifdef USE_MYMATH
#include "MathFunctions.h"
#endif
int main(int argc, char *argv[])
{
if( argc < 2 )
{
fprintf(stdout,"%s Version %d.%d\n", argv[0],
Tutorial_VERSION_MAJOR,
Tutorial_VERSION_MINOR);
fprintf(stdout,"Usage: %s number\n",argv[0]);
return 1;
}
double inputValue = atof(argv[1]);
#ifdef USE_MYMATH
double outputValue = mysqrt(inputValue);
#else
double outputValue = sqrt(inputValue);
#endif
fprintf(stdout,"The square root of %g is %g\n", inputValue, outputValue);
return 0;
}
在源代码中我们也使用了USE_MYMATH。这是通过CMake使用TutorialConfig.h.in配置文件提供给源代码,TutorialConfig.h.in配置文件添加如下代码:
#cmakedefine USE_MYMATH