首先到cmake的网站下载安装cmake
1、第一步
第一步需要掌握的就是编译用cmake 控制一个简单程序的编译,以及把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; }如果要用cmake来控制这个程序的生成,那么就在这个程序的目录下生成一个CMakeLists.txt文件,文件内容如下
cmake_minimum_required (VERSION 2.6) project (Tutorial) add_executable(Tutorial tutorial.cxx)
这时,在命令行模式下,在这个目录下输入两个命令
cmake .
make
即可生成相应的可执行程序
需要说明的是,cmake也可把项目的构建与生成放到其它的文件夹下,比如在当前目录下在建一个目录,名为build则可这样构建
mkdir build
cd build
cmake ..
make
这样所有的中间结果都在build文件夹下,不用改变源代码文件夹的内容
如果我们在cmake里面定义了程序的版本信息,并且要把这个版本信息传递到源代码里去,可以采用这样的方法
先在CMakeLists.txt文件里添加定义,添加后的CMakeLists.txt文件是下面的内容:
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@即可完成参数的传递。