---
title: Make / CMake / Meson 构建系统
url: https://doc.liz6.com/systems-programming/07-toolchain-and-compilation/03-Make-CMake-Meson
locale: zh
area: systems-programming
tags:
- systems-programming
- 工具链与编译
date: 2026-06-30
modified: 2026-06-30
description: '覆盖: GNU Make (pattern rules) → CMake (target-based) → Meson (declarative) → pkg-config → 构建系统选择 适用: C/C++ 项目构建'
---

# Make / CMake / Meson 构建系统

> 覆盖: GNU Make (pattern rules) → CMake (target-based) → Meson (declarative) → pkg-config → 构建系统选择
> 适用: C/C++ 项目构建

## GNU Make

### 核心语法

```makefile
# 基本规则: target: prerequisites → recipe
prog: main.o lib.o
    gcc -o $@ $^            # $@=target, $^=all prerequisites

%.o: %.c                    # pattern rule
    gcc -c -o $@ $<         # $<=first prerequisite

# 变量:
CC := gcc
CFLAGS := -O2 -Wall
LDFLAGS := -lm

# 自动依赖生成:
%.d: %.c
    gcc -MM -MF $@ $<
-include $(OBJS:.o=.d)     # 引入依赖文件
```

## CMake: Target-Based

```cmake
# CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(myproj C)

add_library(mylib STATIC lib.c lib.h)
target_compile_features(mylib PRIVATE c_std_11)

add_executable(prog main.c)
target_link_libraries(prog PRIVATE mylib)

# 查找外部依赖:
find_package(PkgConfig REQUIRED)
pkg_check_modules(ZLIB REQUIRED zlib)
target_link_libraries(prog PRIVATE ${ZLIB_LIBRARIES})
target_include_directories(prog PRIVATE ${ZLIB_INCLUDE_DIRS})
```

## Meson: Declarative

```meson
# meson.build
project('myproj', 'c', version: '1.0')

zlib_dep = dependency('zlib')

mylib = static_library('mylib', 'lib.c', 'lib.h')
executable('prog', 'main.c',
           link_with: mylib,
           dependencies: zlib_dep,
           c_args: ['-O2', '-Wall'])
```

## 三者对比

| | GNU Make | CMake | Meson |
|---|---|---|---|
| 模型 | imperative (怎么做) | target-based | declarative (要什么) |
| 依赖管理 | 手动 | find_package + pkg-config | dependency() 内置 |
| 编译速度 | 基准 | 慢 (configure phase) | 快 (ninja + 缓存) |
| 学习曲线 | 中 | 中高 | 低 |
| IDE 集成 | 弱 | 强 (CLion, VSCode) | 中 |
| Gentoo ebuild | 常见 | 常见 | 增多中 |

## pkg-config

```bash
# 查询已安装库:
pkg-config --cflags --libs zlib     # -I/usr/include -lz
pkg-config --modversion zlib         # 1.2.13

# .pc 文件位置:
ls /usr/lib64/pkgconfig/   # 系统库
ls /usr/share/pkgconfig/   # arch-independent

# 自定义 .pc 文件:
prefix=/usr/local
Name: mylib
Version: 1.0
Cflags: -I${prefix}/include
Libs: -L${prefix}/lib -lmylib
```

## 参考

- **文档**: `info make`, cmake.org/documentation, mesonbuild.com
- **Gentoo**: `man 5 ebuild` (Make 集成)

*关键词: Make, CMake, Meson, pattern rule, target-based, pkg-config, ninja*
