CMake 笔记 | [33] 将源码分成模块

注意
本文最后更新于 2024-02-02,文中内容可能已过时。

一、导言

导言

项目通常从单个**CMakeLists.txt文件开始,随着时间的推移,这个文件会逐渐增长。本篇,我们将演示一种将CMakeLists.txt分割成更小单元的机制。将CMakeLists.txt拆分为模块的动机:**

  • 主CMakeLists.txt更易于阅读;
  • CMake模块可以在其他项目中重用
  • 与函数相结合,模块可以帮助我们限制变量的作用范围。

本篇,我们将演示如何定义和包含一个宏,该宏允许我们获得**CMake的彩色输出(用于重要的状态消息或警告)。**

二、项目结构

1
2
3
4
.
├── cmake
│     └── colors.cmake
└── CMakeLists.txt

https://gitee.com/jiangli01/tutorials/tree/master/cmake-tutorial/chapter7/02

相关源码

cmake/color.cmake

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# colorize CMake output
macro(define_colors)
  if(WIN32)
    # has no effect on WIN32
    set(ColourReset "")
    set(ColourBold "")
    set(Red "")
    set(Green "")
    set(Yellow "")
    set(Blue "")
    set(Magenta "")
    set(Cyan "")
    set(White "")
    set(BoldRed "")
    set(BoldGreen "")
    set(BoldYellow "")
    set(BoldBlue "")
    set(BoldMagenta "")
    set(BoldCyan "")
    set(BoldWhite "")
  else()
    string(ASCII 27 Esc)
    set(ColourReset "${Esc}[m")
    set(ColourBold "${Esc}[1m")
    set(Red "${Esc}[31m")
    set(Green "${Esc}[32m")
    set(Yellow "${Esc}[33m")
    set(Blue "${Esc}[34m")
    set(Magenta "${Esc}[35m")
    set(Cyan "${Esc}[36m")
    set(White "${Esc}[37m")
    set(BoldRed "${Esc}[1;31m")
    set(BoldGreen "${Esc}[1;32m")
    set(BoldYellow "${Esc}[1;33m")
    set(BoldBlue "${Esc}[1;34m")
    set(BoldMagenta "${Esc}[1;35m")
    set(BoldCyan "${Esc}[1;36m")
    set(BoldWhite "${Esc}[1;37m")
  endif()
endmacro()

CMakeLists.txt

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)

project(example LANGUAGES NONE)

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")

include(colors)
define_colors()

message(STATUS "This is a normal message")
message(STATUS "${Red}This is a red${ColourReset}")
message(STATUS "${BoldRed}This is a bold red${ColourReset}")
message(STATUS "${Green}This is a green${ColourReset}")
message(STATUS "${BoldMagenta}This is bold${ColourReset}")
引用
1
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")

cmake子目录添加到CMake模块搜索的路径列表中。

tips
1
2
include(colors)
define_colors()

包括colors.cmake模块,调用其中定义的宏。

引用
1
2
3
4
5
message(STATUS "This is a normal message")
message(STATUS "${Red}This is a red${ColourReset}")
message(STATUS "${BoldRed}This is a bold red${ColourReset}")
message(STATUS "${Green}This is a green${ColourReset}")
message(STATUS "${BoldMagenta}This is bold${ColourReset}")

打印了不同颜色的信息。

三、结果展示

1
2
3
mkdir build
cd build
cmake ..


结果展示

Buy me a coffee~
支付宝
微信
0%