extern 變量聲明static 限制作用域)// Globals.h - 唯一聲明入口
#ifndef GLOBALS_H
#define GLOBALS_H
extern int g_speed;
extern int g_torque;
#endif
// Globals.c - 唯一定義入口
#include "Globals.h"
int g_speed = 0;
int g_torque = 0;
各模組 #include "Globals.h" 即可安全使用,避免重複定義與分散聲明。
// math.h - 公開介面
#ifndef MATH_H
#define MATH_H
#ifdef __cplusplus
extern "C" {
#endif
int add(int a, int b);
double calc_pi(void);
#ifdef __cplusplus
}
#endif
#endif
// math.c - 實現與私有內容
#include "math.h"
#include "Globals.h" // 需要全域變量時
static double pi_cache = 0; // 私有,不暴露
int add(int a, int b) { return a + b; }
僅包含專案級配置宏、通用類型定義,不包含具體模組頭文件,減少編譯依賴。
#ifndef MODULE_H / #define MODULE_H / ... / #endifconst/static 除外)static 限定在 .c 中extern "C" 包裹函數聲明#include "module.h"(自我檢測介面完整性)staticextern(除非引用無頭文件的舊代碼)| 場景 | 方案 |
|---|---|
| 單模組多 .c 文件 | 一個公開 .h,內部 .c 間共享 module_private.h |
| 子模組化 | 主 .h #include "sub1.h" 聚合介面 |
| 純宏/常量庫 | 命名 feature_defs.h,無對應 .c,不包含其他頭文件 |