本文为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.