跨平台工程构建:CMake 的使用 (一)
目录
什么是 CMake

当我们在构建工程时,在不同的平台上使用不同的工具,如在Windows上使用 Visual Studio 工程, 在 Mac 上使用 Xcode 工程。
这些工程只限于特定的平台。当我们需要跨平台构建工程时,就需要使用 CMake 了,它是一个开源的 跨平台系统构建工具 。同一个 CMake 工程可以在不同的平台上转换为与平台适应的工具,极大的方便了跨平台工程构建。
第一个 CMake
新建一个空目录,在其中新建一个文本文件,命名为 CMakeLists.txt,并输入以下内容:
message("Hello,This is my first cmake project")
好了,你的第一个 cmake 工程就已经建好了。接下来,新建一个文件夹 build, 并在该文件夹下运行命令:
cmake ..
你可能会得到以下输出:
-- Building for: Visual Studio 15 2017 -- The C compiler identification is MSVC 19.15.26732.1 -- The CXX compiler identification is MSVC 19.15.26732.1 -- Check for working C compiler: ....../cl.exe -- Check for working C compiler: ....../cl.exe -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working CXX compiler: ....../cl.exe -- Check for working CXX compiler: ....../cl.exe -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done Hello,This is my first cmake project -- Configuring done -- Generating done -- Build files have been written to: ....../build
再来看这个路径下,cmake 生成了一堆文件:

我们成功的使用 cmake 在 Windows 上构建了一个 vs 工程。 当然,如果你的操作系统是 MacOS, 或者 Linux, 结果后有所不同。
其实在 CMakeLists.txt 所以在路径下也能运行 cmake 命令。不过cmake没有提供专门的工具来清理生成的文件,为了方便管理,我们将其生成在 build 目录下。
这个 cmake 工程的作用仅仅是输出一了条消息,并没有什么意义。下面我们来让它更有意义一点:
1) 新建文件 hello.cpp:
#include <iostream>
int main(void){
std::cout << "Hello World" << std::endl;
return 0;
}
2) 修改 CMakeLists.txt :
message("Hello,This is my first project")
# project hello
set(SRC_FILES hello.cpp)
add_executable(hello ${SRC_FILES})
再次运行 cmake 命令,发现这次多了一个名为 hello 的工程,工程中包含了 hello.cpp 。
这就是一个最简单的 cmake 工程。
需要注意的是,CMakeLists.txt 的语法是大小写不敏感的,不管是大写、小写还是混合大小写,都是正确的写法。这里使用小写。
添加版本号与 Config.h配置文件
使用 configure_file 函数可以配置文件,在配置源文件中将配置项以 @@ 标识出来, 在 CMakelists.txt 中给该变量赋值即可。其中最常见的是配置版本号:
配置源文件 config.h.in:
// the configured options and settings #define Hello_VERSION_MAJOR @Hello_VERSION_MAJOR@ #define Hello_VERSION_MINOR @Hello_VERSION_MINOR@ #define The_MACRO @the_macro@
CMakelists.txt:
cmake_minimum_required (VERSION 3.1)
project (HelloCMake)
# The version number
set (Hello_VERSION_MAJOR 1)
set (Hello_VERSION_MINOR 0)
set (the_macro "\"test\"")
#configue a header file to pass some of the CMake settings to 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_executable(HelloCMake src_file.cpp)
经过 cmake 以后输出的配置文件 config.h 如下:
// the configured options and settings #define Hello_VERSION_MAJOR 1 #define Hello_VERSION_MINOR 0 #define The_MACRO "test"
这个文件会出现有我们的工程之中。