(2)CMake入门笔记--CMake官网教程

二. 添加库

现在我们将为我们的项目添加一个库。 该库将包含我们自己的实现,用于计算数字的平方根。 然后,可执行文件可以使用此库而不是编译器提供的标准平方根函数。 在本教程中,我们将把库放入一个名为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的设置来确定是否应编译和使用MathFunction。 请注意,使用变量(在本例中为EXTRA_LIBS)来收集任何可选的库,以便以后链接到可执行文件中。 这是用于保持具有许多可选组件的较大项目清洁的常用方法。

// tutorial.cxx
// 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。 这是通过TutorialConfig.h.in配置文件从CMake提供给源代码,方法是添加以下行:

#cmakedefine USE_MYMATH

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章