About

看作是 Makefile 的 DSL 语法糖吧…

基本的命令形式

command([arg]*) # 参数使用空格分隔, 括号内可以换行
一些基础的命令
  • 设置变量 set(<variable> <value>... [PARENT_SCOPE]) CMake | set
  • 取消设置变量 unset(<variable> [CACHE | PARENT_SCOPE]) CMake | unset
  • 条件判断
    if(<condition>)
      <commands>
    elseif(<condition>) # optional block, can be repeated
      <commands>
    else()              # optional block
      <commands>
    endif()
        

    Cmake | if

  • 历遍
    # foreach(<loop_var> RANGE <stop>)
    # foreach(<loop_var> RANGE <start> <stop> [<step>])
    # foreach(<loop_var> IN [LISTS [<lists>]] [ITEMS [<items>]])
    foreach(<loop_var> <items>)
      <commands>
    endforeach()
        

    CMake | foreach

基本的 CMakeList.txt 的文件结构

# 声明当前项目最低的 CMake 版本
cmake_minimum_required(VERSION 3.10)

# 声明项目名称
project(PROJECT_NAME)

# 编译文件
add_executable(EXECUTABLE_NAME [SOURCE_FILE]+)

# 或以库的形式进行编译:
# add_libaray(LIB_NAME TYPE [SOURCE_FILE]+) # TYPE = STASTIC, SHARED, MODULE

Files

声明一个文件列表.

# Example:
#     file(GLOB sources ${SRC}/*.cc)

file(GLOB <variable> [LIST_DIRECTORIES true|false]
                     [RELATIVE <path>]
                     [CONFIGURE_DEPENDS]
                     <globbing-expressions>...)

CMake | file

复制一些文件.

# Example:
#     configure_file(IN_FILE OUT_FILE COPYONLY)

configure_file(<input> <output>
               [NO_SOURCE_PERMISSIONS | USE_SOURCE_PERMISSIONS |
                FILE_PERMISSIONS <permissions>...]
               [COPYONLY] [ESCAPE_QUOTES] [@ONLY]
               [NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])

CMake | configure_file

Options

为 config 过程提供可选参数.

option(<variable> "<help_text>" [value]) # value = ON / OFF, ...
if (OPTION_NAME)
  # do-some-thing
endif()
解释

效果如下:

cmake .. -DOPTION_NAME=ON

在代码中以宏定义的形式存在:

#ifndef OPTION_NAME
  ...
#else
  ...
#endif

CMake | option

Library

链接库.

target_link_libraries(<target> ... <item>... ...)

CMake | target_link_libraries

Package

导入外部项目.

find_package(<PackageName> [<version>] [REQUIRED] [COMPONENTS <components>...])

CMake | find-package

Include Other CMake

载入并运行其他 CMake 配置文件.

include(<file|module> [OPTIONAL] [RESULT_VARIABLE <var>]
                      [NO_POLICY_SCOPE])

CMake | include

Install

安装编译好的程序.

install(TARGETS <target>... [...])

CMake | install

一些内置的变量

CMake | cmake-variables(7).