CMake使用教程(二)

CMake 是一種跨平臺的免費開源軟件工具,用於使用與編譯器無關的方法來管理軟件的構建過程。在 Android Studio 上進行 NDK 開發默認就是使用 CMake 管理 C/C++ 代碼,所以在學習 NDK 以前最好對 CMake 有必定的瞭解。html

本文主要以翻譯 CMake官方教程文檔爲主,加上本身的一些理解,該教程涵蓋了 CMake 的常見使用場景。因爲能力有限,翻譯部分採用機翻+人工校對,翻譯有問題的地方,說聲抱歉。c++

開發環境:git

  • macOS 10.14.6
  • CMake 3.15.1
  • CLion 2018.2.4

添加「庫」的使用要求

示例程序地址github

使用要求能夠更好地控制庫或可執行文件的連接和包含行,同時還能夠更好地控制 CMake 內部目標的傳遞屬性。利用使用要求的主要命令是:shell

  • target_compile_definitions安全

    給指定目標添加編譯定義。bash

  • target_compile_optionsapp

    給指定目標添加編譯選項。ide

  • target_include_directories函數

    給指定目標添加包含目錄。

  • target_link_libraries

    指定連接給定目標或其依賴項時要使用的庫或標誌。

控制 CMake 內部目標的傳遞屬性有三種類型:

  • PRIVATE

    屬性只應用到本目標,不該用到連接本目標的目標。即生產者須要,消費者不須要。

  • PUBLIC

    屬性既應用到本目標也應用到連接目標的目標。即生產者和消費者都須要。

  • INTERFACE

    屬性不該用到本目標,應用到連接本目標的目標。即生產者不須要,消費者須要。

讓咱們重構代碼「提供選項」項目的代碼,以使用現代 CMake 的使用要求方法。咱們首先聲明,連接到 MathFunctions 的任何人都須要包含當前源目錄,而 MathFunctions 自己不須要。所以,這裏使用 INTERFACE

將如下行添加到 MathFunctions/CMakeLists.txt 的末尾:

# state that anybody linking to us needs to include the current source dir
# to find MathFunctions.h, while we don't.
# 說明與咱們連接的任何人都須要包含當前源目錄才能找到 MathFunctions.h,而咱們不須要。
target_include_directories(MathFunctions
        INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
        )
複製代碼

如今,咱們已經指定了 MathFunction 的使用要求,咱們能夠安全地從頂級 CMakeLists.txt 中刪除對 EXTRA_INCLUDES變量的使用:

if(USE_MYMATH)
  add_subdirectory(MathFunctions)
  list(APPEND EXTRA_LIBS MathFunctions)
endif()

target_include_directories(Tutorial PUBLIC
        "${PROJECT_BINARY_DIR}"
        )
複製代碼

在項目根目錄運行命令編譯項目和生成可執行文件:

cmake -B cmake-build-debug
cmake --build cmake-build-debug
複製代碼

在項目根目錄運行生成的可執行文件:

./cmake-build-debug/Tutorial 2
複製代碼

終端輸出:

Computing sqrt of 2 to be 1.5
Computing sqrt of 2 to be 1.41667
Computing sqrt of 2 to be 1.41422
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
The square root of 2 is 1.41421
複製代碼

安裝

示例程序地址

安裝規則很是簡單:對於 MathFunctions ,咱們要安裝庫和頭文件,對於應用程序,咱們要安裝可執行文件和配置的頭文件。

所以,在 MathFunctions/CMakeLists.txt 的末尾添加:

# install rules
# 安裝規則
install(TARGETS MathFunctions DESTINATION lib)
install(FILES MathFunctions.h DESTINATION include)
複製代碼

並在頂級 CMakeLists.txt 的末尾添加:

# add the install targets
# 添加安裝規則
install(TARGETS Tutorial DESTINATION bin)
install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
        DESTINATION include
        )
複製代碼

這就是本地安裝所需的所有。

在項目根目錄運行命令編譯項目和生成可執行文件:

cmake -B cmake-build-debug
cmake --build cmake-build-debug
複製代碼

在項目根目錄運行命令安裝可執行文件:

cmake --install cmake-build-debug
複製代碼

CMake 從3.15開始使用 cmake --install 安裝文件。CMake 變量 CMAKE_INSTALL_PREFIX 用於肯定文件的安裝根目錄。若是使用 cmake --install,則能夠經過 --prefix 參數指定自定義安裝目錄。對於多配置工具,請使用 --config 參數指定配置。

終端輸出:

-- Install configuration: ""
-- Installing: /usr/local/lib/libMathFunctions.a
-- Installing: /usr/local/include/MathFunctions.h
-- Installing: /usr/local/bin/Tutorial
-- Installing: /usr/local/include/TutorialConfig.h
複製代碼

在項目根目錄執行命令:

Tutorial 2
複製代碼

終端輸出:

Computing sqrt of 2 to be 1.5
Computing sqrt of 2 to be 1.41667
Computing sqrt of 2 to be 1.41422
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
Computing sqrt of 2 to be 1.41421
The square root of 2 is 1.41421
複製代碼

這個時候咱們調用的不是 cmake-build-debug 下的 Tutorial 文件,而是安裝到 /usr/local/bin 目錄下的 Tutorial 文件。咱們能夠經過命令查看一下 Tutorial 的位置:

where Tutorial
複製代碼

終端輸出:

/usr/local/bin/Tutorial
複製代碼

測試

示例程序地址

接下來,測試咱們的應用程序。在頂級 CMakeLists 文件的末尾,咱們能夠啓用測試,而後添加一些基本測試以驗證應用程序是否正常運行。

# enable testing
# 啓用測試
enable_testing()

# does the application run
# 測試應用程序是否運行
add_test(NAME Runs COMMAND Tutorial 25)

# does the usage message work?
# 測試消息是否工做?
add_test(NAME Usage COMMAND Tutorial)
set_tests_properties(Usage
        PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
        )

# define a function to simplify adding tests
# 定義一個函數以簡化添加測試
function(do_test target arg result)
    add_test(NAME Comp${arg} COMMAND ${target} ${arg})
    set_tests_properties(Comp${arg}
            PROPERTIES PASS_REGULAR_EXPRESSION ${result}
            )
endfunction(do_test)

# do a bunch of result based tests
# 作一堆基於結果的測試
do_test(Tutorial 4 "4 is 2")
do_test(Tutorial 9 "9 is 3")
do_test(Tutorial 5 "5 is 2.236")
do_test(Tutorial 7 "7 is 2.645")
do_test(Tutorial 25 "25 is 5")
do_test(Tutorial -25 "-25 is [-nan|nan|0]")
do_test(Tutorial 0.0001 "0.0001 is 0.01")
複製代碼

第一個測試只是驗證應用程序正在運行,沒有段錯誤或其餘崩潰,而且返回值爲零。這是 CTest 測試的基本形式。

下一個測試使用 PASS_REGULAR_EXPRESSION 測試屬性來驗證測試的輸出是否包含某些字符串。在這種狀況下,驗證在提供了錯誤數量的參數時是否打印了用法消息。

最後,咱們有一個名爲 do_test 的函數,該函數運行應用程序並驗證所計算的平方根對於給定輸入是否正確。對於 do_test 的每次調用,都會基於傳遞的參數將另外一個測試添加到項目中,該測試具備名稱,輸入和預期結果。

在項目根目錄運行命令編譯項目和生成可執行文件:

cmake -B cmake-build-debug
cmake --build cmake-build-debug
複製代碼

在項目根目錄運行命令測試應用程序:

cd cmake-build-debug
ctest
複製代碼

終端輸出:

Test project /Users/taylor/Project/Taylor/C/Study/cmake-tutorial/cmake-test/cmake-build-debug
    Start 1: Runs
1/9 Test #1: Runs ............................. Passed 0.00 sec
    Start 2: Usage
2/9 Test #2: Usage ............................ Passed 0.00 sec
    Start 3: Comp4
3/9 Test #3: Comp4 ............................ Passed 0.00 sec
    Start 4: Comp9
4/9 Test #4: Comp9 ............................ Passed 0.00 sec
    Start 5: Comp5
5/9 Test #5: Comp5 ............................ Passed 0.00 sec
    Start 6: Comp7
6/9 Test #6: Comp7 ............................ Passed 0.00 sec
    Start 7: Comp25
7/9 Test #7: Comp25 ........................... Passed 0.00 sec
    Start 8: Comp-25
8/9 Test #8: Comp-25 .......................... Passed 0.00 sec
    Start 9: Comp0.0001
9/9 Test #9: Comp0.0001 ....................... Passed 0.00 sec

100% tests passed, 0 tests failed out of 9

Total Test time (real) =   0.03 sec
複製代碼

系統自檢

示例程序地址

讓咱們考慮向咱們的項目中添加一些代碼,這些代碼取決於目標平臺可能不具有的功能。

對於此示例,咱們將添加一些代碼,具體取決於目標平臺是否具備 logexp 函數。固然,幾乎每一個平臺都具備這些功能,但對於本教程而言,假定它們並不常見。

若是平臺具備 logexp ,那麼咱們將使用它們來計算 mysqrt 函數中的平方根。咱們首先在頂級 CMakeList 中使用 CheckSymbolExists.cmake 宏測試這些功能的可用性。

# does this system provide the log and exp functions?
# 該系統是否提供log和exp函數?
include(CheckSymbolExists)
set(CMAKE_REQUIRED_LIBRARIES "m")
check_symbol_exists(log "math.h" HAVE_LOG)
check_symbol_exists(exp "math.h" HAVE_EXP)
複製代碼

TutorialConfig.hconfigure_file 命令以前完成對 logexp 的測試很是重要,configure_file 命令使用 CMake 中的當前設置當即配置文件,因此 check_symbol_exists 命令應該放在 configure_file 以前。

如今,將這些定義添加到 TutorialConfig.h.in 中,以便咱們能夠從 mysqrt.cxx中使用它們:

// does the platform provide exp and log functions?
// 平臺是否提供log和exp函數?
#cmakedefine HAVE_LOG
#cmakedefine HAVE_EXP
複製代碼

更新 MathFunctions/CMakeLists.txt 文件,以便 mysqrt.cxx知道此文件的位置:

target_include_directories(MathFunctions
          INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
          PRIVATE ${CMAKE_BINARY_DIR}
          )
複製代碼

修改 mysqrt.cxx 以包含 cmathTutorialConfig.h。接下來,在 mysqrt函數的同一文件中,咱們可使用如下代碼(若是在系統上可用)提供基於 logexp 的替代實現(在返回結果前不要忘記 #endif !):

咱們將在 TutorialConfig.h.in 中使用新定義,所以請確保在配置該文件以前進行設置。

#if defined(HAVE_LOG) && defined(HAVE_EXP)
    double result = exp(log(x) * 0.5);
    std::cout << "Computing sqrt of " << x << " to be " << result
              << " using log and exp" << std::endl;
#else
    double result = x;
    // do ten iterations
    for (int i = 0; i < 10; ++i) {
        if (result <= 0) {
            result = 0.1;
        }
        double delta = x - (result * result);
        result = result + 0.5 * delta / result;
        std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
    }
#endif
複製代碼

在項目根目錄運行命令編譯項目和生成可執行文件:

cmake -B cmake-build-debug
cmake --build cmake-build-debug
複製代碼

在項目根目錄運行生成的可執行文件:

./cmake-build-debug/Tutorial 2
複製代碼

終端輸出:

Computing sqrt of 2 to be 1.41421 using log and exp
The square root of 2 is 1.41421
複製代碼

CMake使用教程系列文章

相關文章
相關標籤/搜索