本示例文件見上一篇博文,英文原文見https://cmake.org/cmake/help/v3.17/guide/tutorial/index.html#a-basic-starting-point-step-1
現(xiàn)在,我們將庫添加到我們的項(xiàng)目中。 該庫將包含我們自己的實(shí)現(xiàn),用于計算數(shù)字的平方根。 然后可執(zhí)行文件可以使用此庫而不是編譯器提供的標(biāo)準(zhǔn)平方根函數(shù)。
在本教程中,我們將庫放入名為MathFunctions的子目錄中。 該目錄已包含頭文件MathFunctions.h和源文件mysqrt.cxx。 源文件具有一個稱為mysqrt的函數(shù),該函數(shù)提供與編譯器的sqrt函數(shù)類似的功能。
1 添加add_library命令(在MathFunctions文件夾下的CMakeLists.txt文件中)
將以下一行CMakeLists.txt文件添加到MathFunctions目錄:
add_library(MathFunctions mysqrt.cxx)
2 利用add_subdirectory命令添加子目錄到項(xiàng)目中
為了使用新庫,我們將在頂層CMakeLists.txt文件中添加add_subdirectory()以便構(gòu)建該和調(diào)用該庫。 我們將新庫添加到可執(zhí)行文件,并將MathFunctions添加為包含目錄,以便可以找到mqsqrt.h頭文件。 現(xiàn)在,頂層CMakeLists.txt文件的最后幾行應(yīng)如下所示:
# 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" #添加頭文件目錄
)
3 將使用庫設(shè)為可選項(xiàng)
現(xiàn)在讓我們將MathFunctions庫設(shè)為可選。 雖然對于本教程確實(shí)沒有任何必要,但是對于大型項(xiàng)目,這是很常見的。 第一步是向頂級CMakeLists.txt文件添加一個選項(xiàng)。
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)
此選項(xiàng)將顯示在cmake-gui和ccmake中,默認(rèn)值ON可由用戶更改。 此設(shè)置將存儲在緩存中,因此用戶無需在每次在構(gòu)建目錄上運(yùn)行CMake時都設(shè)置該值。在dos命令行中打開或者關(guān)閉該庫的使用如下"-DUSE_MYMATH=ON"或者"-DUSE_MUMATH=OFF"即可
4 編寫if語句
下一個更改是使建立和鏈接MathFunctions庫成為條件。 為此,我們將頂級CMakeLists.txt文件的結(jié)尾更改為如下所示:
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來收集所有可選庫,以供以后鏈接到可執(zhí)行文件中。 變量EXTRA_INCLUDES類似地用于可選的頭文件。 在處理許多可選組件時,這是一種經(jīng)典方法,我們將在下一步中介紹現(xiàn)代方法。
5 對源代碼的更改
對源代碼的相應(yīng)更改非常簡單。 首先,如果需要,請在tutorial.cxx中包含MathFunctions.h頭文件:
#ifdef USE_MYMATH
# include "MathFunctions.h"
#endif
然后,在同一文件中,使USE_MYMATH控制使用哪個平方根函數(shù):
#ifdef USE_MYMATH
const double outputValue = mysqrt(inputValue);
#else
const double outputValue = sqrt(inputValue);
#endif
由于源代碼現(xiàn)在需要USE_MYMATH,因此我們可以使用以下行將其添加到TutorialConfig.h.in中:
#cmakedefine USE_MYMATH
6配置
請注意,在dos下執(zhí)行命令時,可以利用-DCMAKE_BUILD_TYPE=Debug -DUSE_MYMATH=ON命令來控制使用庫,如圖1所示,那么,配置完成的CMakeCache.txt文件中的結(jié)果圖2所示。


7 創(chuàng)建
創(chuàng)建命令執(zhí)行結(jié)果如下:

8 測試

利用了迭代求解,說明調(diào)用庫成功。
--青春未腐,光陰還長!--2020.05.04