本文為CMake官方教程翻譯文檔。
英文原文地址:http://www.cmake.org/cmake/help/cmake_tutorial.html
對應源碼下載地址:http://public.kitware.com/cgi-bin/viewcvs.cgi/Tests/Tutorial.tar.gz?root=CMake&view=tar
第一步:一個基礎入門例子
大多數的源碼都會編譯為可執行文件,對於簡單的工程只需要兩行的CMakeLists.txt文件就行了,我們從這里開始我們的CMake之旅。
CMakeLists.txt文件如下:
cmake_minimum_required (VERSION 2.6)
project (Tutorial)
add_executable(Tutorial tutorial.cxx)
注意到這個例子里面全部命令使用小寫,CMake支持大寫、小寫或者混合大小寫命令。tutorial.cxx文件中的源碼會計算一個數的平方根,第一個版本的會非常簡單,代碼如下:
// A simple program that computes the square root of a number #include <stdio.h> #include <stdlib.h> #include <math.h> int main (int argc, char *argv[]) { if (argc < 2) { fprintf(stdout,"Usage: %s number\n",argv[0]); return 1; } double inputValue = atof(argv[1]); double outputValue = sqrt(inputValue); fprintf(stdout,"The square root of %g is %g\n", inputValue, outputValue); return 0; }
添加一個版本號和配置頭文件
我們要添加的第一個功能就是為我們的可運行程序和項目提供一個版本號。你可以在源碼中專門做這件事,CMakeLists文件提供更靈活的方式來實現。添加了版本號的CMakeLists文件如下:
cmake_minimum_required (VERSION 2.6) project (Tutorial) # The version number. set (Tutorial_VERSION_MAJOR 1) set (Tutorial_VERSION_MINOR 0) # configure a header file to pass some of the CMake settings # to the source code configure_file ( "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in" "${PROJECT_BINARY_DIR}/TutorialConfig.h" ) # add the binary tree to the search path for include files # so that we will find TutorialConfig.h include_directories("${PROJECT_BINARY_DIR}") # add the executable add_executable(Tutorial tutorial.cxx)
在我們的源碼樹種編寫配置文件之后,我們還需要把路徑添加到包含文件的搜索路徑中。在我們的源碼樹中創建一個TutorialConfig.h.in文件,內容如下:
// the configured options and settings for Tutorial #define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@ #define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
當CMake配置這個頭文件的時候,使用CMakeLists文件中的變量替換@Tutorial_VERSION_MAJOR@ 和 @Tutorial_VERSION_MINOR@ 。接下來修改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" 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]); double outputValue = sqrt(inputValue); fprintf(stdout,"The square root of %g is %g\n", inputValue, outputValue); return 0; }
主要的變化是包含了TutorialConfig.h頭文件,在Usage信息中輸出版本號。
至此一個簡單的項目就創建完成了,我們再源碼中創建build目錄,使用命令行進入build目錄。
運行:
cmake ..
make
即可生成項目,通過為CMake添加-G參數來生成不同平台的makefile文件
運行Tutorial會提示帶版本號的Usage信息,輸入Tutorial 25 可以計算25的平方根為5.