CMake入门1:概述与基本语法
0 CMake介绍
-
CMake 是个开源的跨平台自动化建构系统。 用来管理软件配置的程序,并不依赖于某个特定编译器。 并可支持多层目录、多个应用程序、多个库。 CMake的配置文件取名为CMakeLists.txt。 CMake配置文件(CMakeLists.txt)可设置源代码或目标程序库的路径、产生适配器(wrapper)、还可以用任意的顺序建构可执行文件。 CMake也支持静态与动态程序库的建构。 CMake并不直接建构出最终的软件,而是产生标准的建构档。(如Windows下.sln工程)
1 基本语法
一个最基本的CmakeLists.txt文件最少需要包含以下三行:
-
注意:cmake的语法支持大小、小写和大小写混合上边的代码中我们使用的cmake语法是小写的
cmake_minimum_required (VERSION 2.6) project (Tutorial) add_executable(Tutorial tutorial.cpp)
Demo1:创建一个tutorial.cpp文件
// 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
", argv[0]);
return 1;
}
double inputValue = atof(argv[1]);
double outputValue = sqrt(inputValue);
fprintf(stdout, "The square root of %g is %g
",
inputValue, outputValue);
return 0;
}
2 构建程序
用cmake来编译这段代码
cmake .
在Windows下:
即可生成可执行程序Tutorial。
3 添加版本号
如何给程序添加版本号和带有使用版本号的头文件。
set(KEY VALUE) 接受两个参数,用来声明变量。 在cmake中使用 KEY 并不能直接获得 VALUE 的值。 必须使用 ${KEY}
# CMake最低版本要求
cmake_minimum_required (VERSION 2.6)
# 项目名称
project (Tutorial)
# 使用变量,添加版本号
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
# 配置一个头文件来传递一些CMake的设置信息
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
# 添加 binary tree 让我们可以搜到所需文件
include_directories("${PROJECT_BINARY_DIR}")
# 添加源文件
add_executable(Tutorial tutorial.cpp)
配置文件将会被写入到可执行文件目录下。 我们的项目必须包含这个文件夹来使用这些配置头文件。 需要在工程目录下新建一个TutorialConfig.h.in。
// the configured options and settings for Tutorial #define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@ #define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
然后即可在 Tutorial.cpp #include TutorialConfig.h即可使用刚定义的宏定义。
构建程序之后,会生成 TutorialConfig.h
