二. 添加庫
現在我們將爲我們的項目添加一個庫。 該庫將包含我們自己的實現,用於計算數字的平方根。 然後,可執行文件可以使用此庫而不是編譯器提供的標準平方根函數。 在本教程中,我們將把庫放入一個名爲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