大型 C 項目通過分層架構 + 模塊化設計 實現:高內聚、低耦合、可擴展、可維護、可移植、可測試。
+------------------------+ | 應用層 | 業務邏輯、用戶界面 +------------------------+ | 功能/服務層 | 協議棧、文件系統、診斷服務 +------------------------+ | 作業系統抽象層 (OSAL)| 任務、信號量、內存、定時器 +------------------------+ | 驅動層 (HAL/BSP) | GPIO、UART、SPI、I2C、Flash +------------------------+ | 硬件 | +------------------------+
上層只調用下層公開接口,下層不知上層存在。同層模塊通過接口通信。
project/ ├── config/ # 裁剪宏、專案配置 (config.h) ├── common/ # 通用類型、工具、斷言 ├── hal/ # 硬件抽象層 │ ├── inc/ # 對外接口 │ └── src/ # 實現 ├── osal/ # OS 抽象層 ├── modules/ # 功能模塊 │ ├── comm/ # 通信協議 │ │ ├── inc/comm.h │ │ └── src/comm.c │ ├── storage/ # 存儲管理 │ └── diag/ # 診斷服務 ├── app/ # 應用入口 └── build/ # 構建腳本、鏈接腳本
#ifndef MODULE_FOO_H
#define MODULE_FOO_H
#ifdef __cplusplus
extern "C" {
#endif
// 接口聲明...
#ifdef __cplusplus
}
#endif
#endif
| 允許在 .h 中 | 禁止在 .h 中 |
|---|---|
| 宏定義、類型定義 (typedef/struct/union/enum) | 可執行代碼 (函數體) |
| 函數聲明、extern 變量聲明 | 變量定義 (會導致多重定義) |
| 常量聲明 (extern const) | 內部數據結構、私有宏、靜態函數 |
| 內聯函數 (inline/static inline) |
/**
* @brief 初始化通信模塊
* @param config 配置參數,不可為 NULL
* @return 0 成功,負值錯誤碼
* @note 必須在系統啟動早期調用,線程不安全
*/
int comm_init(const CommConfig *config);
// foo.c
#include "foo.h" // 自檢接口一致性
#include "foo_private.h" // 內部定義
#include "common/log.h" // 依賴的公共設施
// 內部靜態變量/函數 → static 限制作用域
static int foo_state = 0;
static void foo_internal_helper(void) { ... }
// 導出函數實現
int foo_init(const FooConfig *cfg) {
// 參數檢查
if (!cfg) return -ERR_INVAL;
...
}
// cpp_wrapper.h
#ifdef __cplusplus
extern "C" {
#endif
void cpp_api_init(void);
int cpp_api_process(int x);
#ifdef __cplusplus
}
#endif
// cpp_wrapper.cpp
#include "cpp_wrapper.h"
#include "RealCppClass.hpp"
void cpp_api_init(void) { RealCppClass::instance().init(); }
int cpp_api_process(int x) { return RealCppClass::instance().process(x); }
// asm_func.S (GNU as)
.global asm_func
.type asm_func, @function
asm_func:
// 參數在 r0 (ARM) / rdi (x86_64)
add r0, r0, #1
bx lr
// C 端聲明
extern int asm_func(int x);