CMake 是目前最主流的 C/C++ 构建工具之一,具备跨平台、模块化、维护性强等优势。本文将以你提供的多模块 C 项目为例,介绍如何使用现代 CMake:
your_project/
├── CMakeLists.txt # 顶层构建脚本
├── include/ # 所有模块的公共头文件
│ ├── art.h
│ ├── color.h
│ └── password.h
├── src/ # 源文件和子模块
│ ├── main.c # 主程序入口
│ ├── art/
│ │ ├── art.c
│ │ └── CMakeLists.txt
│ ├── color/
│ │ ├── color.c
│ │ └── CMakeLists.txt
│ └── password/
│ ├── password.c
│ └── CMakeLists.txt
└── build/ # 构建输出目录(自动生成)
这是项目的统一构建入口:
cmake_minimum_required(VERSION 3.10)
project(MyApp C)
set(CMAKE_C_STANDARD 99)
# 设置输出目录
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# 添加模块构建目录
add_subdirectory(src/art)
add_subdirectory(src/color)
add_subdirectory(src/password)
# 构建主程序
add_executable(${PROJECT_NAME} src/main.c)
# 链接静态库
target_link_libraries(${PROJECT_NAME}
PRIVATE
art
color
password
)
add_library(art STATIC art.c)
target_include_directories(art PUBLIC ${CMAKE_SOURCE_DIR}/include)
add_library(color STATIC color.c)
target_include_directories(color PUBLIC ${CMAKE_SOURCE_DIR}/include)
add_library(password STATIC password.c)
target_include_directories(password PUBLIC ${CMAKE_SOURCE_DIR}/include)
#ifndef ART_H
#define ART_H
void set_art(void);
#endif
#include <stdio.h>
#include "art.h"
void set_art(void) {
printf("Art module called.\n");
}
#ifndef COLOR_H
#define COLOR_H
void set_color(void);
#endif
#include <stdio.h>
#include "color.h"
void set_color(void) {
printf("Color module called.\n");
}
#ifndef PASSWORD_H
#define PASSWORD_H
void check_password(void);
#endif
#include <stdio.h>
#include "password.h"
void check_password(void) {
printf("Password checked.\n");
}
#include "art.h"
#include "color.h"
#include "password.h"
int main(void) {
set_art();
set_color();
check_password();
return 0;
}
在项目根目录下执行以下命令:
mkdir build
cd build
cmake ..
cmake --build .
如果使用 MinGW 构建(Windows):
cmake -G "MinGW Makefiles" ..
mingw32-make
构建完成后:
./bin/MyApp # Linux/macOS
.\bin\MyApp.exe # Windows
Art module called.
Color module called.
Password checked.
输出目录 | 内容 |
---|---|
build/bin/ | 可执行程序 MyApp |
build/lib/ | 模块静态库 libart.a、libcolor.a、libpassword.a |
特性 | 描述 |
---|---|
模块化构建 | 每个模块独立,便于维护和复用 |
跨平台支持 | CMake 可输出 Makefile、Ninja、Visual Studio 工程 |
可维护性强 | 项目结构清晰,新增模块无需改动主流程 |
现代风格 CMake | 使用 target_* 系列命令,更安全更显式 |
STATIC
改为 SHARED
)target_precompile_headers()
加速编译build/
├── bin/
│ └── MyApp.exe
├── lib/
│ ├── libart.a
│ ├── libcolor.a
│ └── libpassword.a
├── CMakeFiles/ # 构建中间文件,可删除
├── CMakeCache.txt # 构建缓存,可删除
└── MyApp.sln # Visual Studio 生成的解决方案(若使用)
若只需产物,可拷贝
bin/
和lib/
到output/
,其余中间文件可清理。
清理构建只需删除 build/
:
rm -rf build/ # macOS / Linux
rd /s /q build # Windows PowerShell
借助 CMake,你可以快速构建跨平台、结构清晰、模块可扩展的 C 项目。本文展示了从目录设计、模块组织到构建输出的完整流程,是进行中大型 C 项目的理想模板。