码迷,mamicode.com
首页 > 其他好文 > 详细

CMake tutorial 翻译

时间:2016-05-04 17:20:16      阅读:458      评论:0      收藏:0      [点我收藏+]

标签:

1.最简实例

  使用cmake的最简实例是由一个源程序文件生成一个可执行文件。例如由下述C++源程序文件生成可执行文件tutorial。

  main.cpp

#include<iostream>
using namespace std;
int main(){

    cout<<"hello world"<<endl;
}

  需要编辑CMakeLists.txt文件如下:

cmake_minimum_required(VERSION 2.6)
project (tutorial)
add_executable(tutorial main.cpp)

  其中cmake_minimum_required指定了cmake最低版本限制,project指定了项目名称,add_executable指定了生成的可执行文件名称为tutorial,源程序文件为main.cpp。

  需要生成项目可以cd到此目录,然后依次执行下述命令:

cmake .
make 

  可见,cmake帮助我们快速生成了项目的makefile文件,从而可以通过make命令直接生成项目的可执行文件。此时,在该路径下就生成了可执行文件tutorial,执行该程序,有:

技术分享

  使用cmake就是如此简单快捷!

2.设置版本号和配置头文件

  如果在cmake中指定版本号这样更加灵活,我们可以这么操作:通过CMakeLists.txt文件指定版本号,然后通过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}/config.h.in"
  "${PROJECT_BINARY_DIR}/config.h"
  )
 
# add the binary tree to the search path for include files
# so that we will find config.h
include_directories("${PROJECT_BINARY_DIR}")
 
# add the executable
add_executable(Tutorial main.cpp)

  config.h.in 中引用了CMakeLists.txt中定义的两个版本号,如下所示:

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

  main.cpp文件直接引用config.h头文件中定义的版本号,如下所示:

#include "config.h"
#include<iostream>
using namespace std;
int main(){
    cout<<"Tutorial_VERSION_MAJOR: "<<Tutorial_VERSION_MAJOR<<endl;
    cout<<"Tutorial_VERSION_MINOR: "<<Tutorial_VERSION_MINOR<<endl;
    cout<<"hello world"<<endl;
    return 0;

}

  此时,执行命令cmake不仅生成了makefile文件,还链接生成了config.h文件,如下所示:

#define Tutorial_VERSION_MAJOR 1
#define Tutorial_VERSION_MINOR 0

  执行命令make,然后顺利生成了可执行文件Tutorial,执行该文件有:

技术分享

  完美!

3.在项目中添加库

 

CMake tutorial 翻译

标签:

原文地址:http://www.cnblogs.com/zhoudayang/p/5458861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!