cmake教程

step 1   开始

创建一个最简单到CMakeLists文件 : CMakeLists.txt 

1 cmake_minimum_required (VERSION 2.6)  
2 project (Tutorial)
3 add_executable (Tutorail tutorial.c)

然后创建源文件: tutorial.c

 1 // A simple program that computes the square root of a number
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <math.h>
 5 int main (int argc, char *argv[])
 6 {
 7   if (argc < 2)
 8     {
 9     fprintf(stdout,"Usage: %s number\n",argv[0]);
10     return 1;
11     }
12   double inputValue = atof(argv[1]);
13   double outputValue = sqrt(inputValue);
14   fprintf(stdout,"The square root of %g is %g\n",
15           inputValue, outputValue);
16   return 0;
17 }

拥有这两个文件之后就可以利用cmake 从源码构建一个执行文件 :

1 cmake CMakeLists.txt

或者:

1 cmake .                      

cmake的语法为:

cmake  [optoins]  <path-to-source>
    或者
cmake  [options] <path-to-existing-build>

接下来我们为项目和可执行文件增加版本数字和配置头文件, 更改上面的CMakeList.txt文件为:

 1 cmake_minimum_required (VERSION 2.6)
 2 project (Tutorial)
 3 
 4 # The version number
 5 set (Tutorial_VERSION_MAJOR 1)
 6 set (Tutorial_VERSION_MINOR 0)
 7 
 8 # configure a header file to pass some of CMake settings to the source code
 9 configure_file    (
10     "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
11     "${PROJECT_BINARY_DIR}/TutorialConfig.h"
12     )
13 
14 #add the binary tree to the search path for include files so that we will find TutorialConfig.h
15 include_directories ("${PROJECT_BINARY_DIR}" )
16 
17 #add the executable
18 add_executable (Tutorial tutorial.c)

在源码目录下添加 TutorialConfig.h.in文件,内容如下:

// the configured options and setting for Tutorial 

#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@

CMake会根据CMakeLists.txt文件中设置的 Tutorial_VERSION_MAJOR 和 Tutorial_VERSION_MINOR 的值,替换掉TutorialConfig.h.in文件中的@Tutorial_VERSION_MAJOR@  ,@Tutorial_VERSION_MINOR@ .

 

attention:

  在最后的 Tutorial.c文件中, 使用了 #include <TutoriaConfig.h>文件.   这个文件是在执行cmake之后更具 TutorialConfig.h.in文件生成的.

summary

  step 1 完成了 利用cmake从源文件构建一个可执行项目的过程 ,并为项目和和可执行文件添加了版本数字和配置头文件.

step 1

posted @ 2013-12-04 23:04  mayer21548  阅读(1567)  评论(0编辑  收藏  举报