Cmake是一个编译、构建工具。使用CMakeLists.txt来描述构建过程,能够生成标准的构建文件,如Makefile。通常先编写CMakeLists.txt,而后经过cmake来生成Makefile,最后执行make进行编译。html
在ubuntu上安装cmake很是简单,执行sudo apt-get install cmake便可。若是想安装最新的cmake版本,就须要本身进行源码编译安装。源码下载路径:https://cmake.org/download。源码编译安装很是简单,这里就再也不详细描述了。ubuntu
cmake安装完成后,执行cmake --version,便可查看cmake的版本号。个人是3.5.1ide
这里给出一个简单的使用cmake进行构建的工程示例,目录结构以下:工具
test01
├── build
├── CMakeLists.txt
└── main.cui
main.c文件以下:url
#include <stdio.h> int main(int argc, char** argv) { printf("hello cmake\n"); return 0; }
CMakeLists.txt内容以下:code
#设置cmake的最小版本 CMAKE_MINIMUM_REQUIRED(VERSION 2.6) #设置项目名称 project(test01) #设置源文件 aux_source_directory(. dir_srcs) #设置可执行程序 add_executable(test01 ${dir_srcs})
我这里mkdir 了build 目录,htm
cd buildip
cmake ..ci
make
最后就会在当前目录下看到生成的test01可执行程序。
接下来,对上例中的CMakeLists.txt的语法进行解释。
CMakeLists.txt 的语法比较简单,由命令、注释和空格组成,其中命令是不区分大小写的,符号"#"后面的内容被认为是注释。
Call the
cmake_minimum_required()
command at the beginning of the top-levelCMakeLists.txt
file even before calling theproject()
command. It is important to establish version and policy settings before invoking other commands whose behavior they may affect. See also policyCMP0000
.
cmake_minimun_required
格式:cmake_minimum_required(VERSION <min>[...<max>][FATAL_ERROR])
设置该工程的cmake最低支持版本,注意"VERSION"不能写成小写,不然会报cmake_minimum_required called with unknown argument "version".
project
project(<PROJECT-NAME> [LANGUAGES] [<language-name>...]) project(<PROJECT-NAME> [VERSION <major>[.<minor>[.<patch>[.<tweak>]]]] [DESCRIPTION <project-description-string>] [HOMEPAGE_URL <url-string>] [LANGUAGES <language-name>...])
aux_source_directory
aux_source_directory(<dir> <variable>)
Find all source files in a directory.Collects the names of all the source files in the specified directory and stores the list in the
add_executable
add_executable(<name> [WIN32] [MACOSX_BUNDLE] [EXCLUDE_FROM_ALL] [source1] [source2 ...])
将源文件编译成可执行程序,可执行程序的名称由
补充:
cmake的命令包含 scripting commands,project commands,ctest commands,deprecated commands。