CMake 学习笔记

CMake 通常用于跨平台、跨 IDE 开发,在 Linux 下它能生成 Makefile,在 Windows 下又能生成 .sln 项目文件。

创建如下的目录结构:

my_project
|-- src/
|-- build/
|-- include/
`-- CMakeLists.txt
  • src:存放源文件和私有头文件的目录

  • build :存放 CMake 的生成文件的目录

  • include :存放对外暴露的公有头文件的目录

  • CMakeLists.txt:CMake 的配置文件

基础使用流程

默认流程

> cd build
> cmake ..
> make

命令行参数

-G flag 用于指定生成器。

查询支持的生成器:

> cmake --help
...
Generators

The following generators are available on this platform:
  Unix Makefiles              = Generates standard UNIX makefiles.
  Ninja                       = Generates build.ninja files (experimental).
  CodeBlocks - Ninja          = Generates CodeBlocks project files.
  CodeBlocks - Unix Makefiles = Generates CodeBlocks project files.
  Eclipse CDT4 - Ninja        = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Unix Makefiles
                              = Generates Eclipse CDT 4.0 project files.
  KDevelop3                   = Generates KDevelop 3 project files.
  KDevelop3 - Unix Makefiles  = Generates KDevelop 3 project files.
  Sublime Text 2 - Ninja      = Generates Sublime Text 2 project files.
  Sublime Text 2 - Unix Makefiles
                              = Generates Sublime Text 2 project files.

例子:

cmake -G "Ninja" # Example

-D flag 用于设置变量,例子:

cmake -D CMAKE_BUILD_TYPE=Release

-B flag 用于设置构建目录:

cmake .. -B build
make

编写配置文件

CMakeLists.txt:

cmake_minimum_required(VERSION 2.6)
project (minimal_example) # 设置项目名称

add_executable (Example src/example.cpp) # 可执行文件的位置,Example 是可执行文件的名称

src/example.cpp

#include <iostream>
int main(int argc, char const *argv[])
{
    std::cout << "Example!\n";
    return 0;
}

执行:

> cd build
> make clean
> make
[100%] Building CXX object CMakeFiles/Example.dir/src/example.cpp.o
Linking CXX executable Example
[100%] Built target Example
> ./Example
Example!

变量

# Set variables
set(VARIABLE_NAME "value")
set(WOW_NUM 10)

# Or even as a list!
# Lists are just semi-colon delimited strings!
set(SOME_LIST "a" "b")
set(EQUIVALENT_LIST "a;b") # These are the same!

set(NUM_LIST 1 2)
set(EQUIVALENT_NUM_LIST 1;2)

# You can even append to the lists!
set(NUM_LIST ${NUM_LIST} 3 4) # So-so way
list(APPEND NUM_LIST 5 6) # Better way

实践

我们来写一个矩阵计算的小项目来实践一下。

$ mkdir ~/cpp/cmake_learning/matrix_util -p
$ cd $_

参阅

[01 CMake - Basics and Scripting.md](https://github.com/methylDragon/coding-notes/blob/master/CMake/01 CMake - Basics and Scripting.md)