模組包含介面(宣告功能)與實作(具體演算法/資料結構)。介面隱藏細節以降低耦合,實作可多樣化但需符合介面契約。C語言透過頭檔(.h)宣告介面,.c 提供實作,客戶端 #include 介面,實作 #include 介面確保一致性。
Aritharith.h#ifndef ARITH_H #define ARITH_H int Arith_max(int x, int y); int Arith_min(int x, int y); int Arith_div(int x, int y); // 向負無窮取整除法 int Arith_mod(int x, int y); // 對應餘數:x - y * Arith_div(x,y) int Arith_ceiling(int x, int y); // 不小於商的最小整數 int Arith_floor(int x, int y); // 不超過商的最大整數 #endif
介面名 Arith 作為前綴避免命名衝突。提供標準庫缺失的良好定義除法/取模語義(標準 C 向零取整,實作相關)。
arith.c#include "arith.h"
int Arith_max(int x, int y) { return x > y ? x : y; }
int Arith_min(int x, int y) { return x > y ? y : x; }
int Arith_div(int x, int y) {
int q = x / y, r = x % y;
if (r != 0 && ((r > 0) != (y > 0))) q--; // 向負無窮調整
return q;
}
int Arith_mod(int x, int y) { return x - y * Arith_div(x, y); }
int Arith_ceiling(int x, int y) { return -Arith_div(-x, y); }
int Arith_floor(int x, int y) { return Arith_div(x, y); }
Stackstack.h#ifndef STACK_H #define STACK_H typedef struct Stack_T *Stack_T; // 不透明指標,隱藏內部結構 Stack_T Stack_new(void); int Stack_empty(Stack_T stk); void Stack_push(Stack_T stk, void *x); void *Stack_pop(Stack_T stk); void Stack_free(Stack_T *stk); #endif
stack.c#include <stddef.h> #include <assert.h> #include "mem.h" #include "stack.h"
#define T Stack_T
struct T {
int count;
struct elem { void *x; struct elem *link; } *head;
};
T Stack_new(void) {
T stk; NEW(stk); // NEW 為 mem.h 巨集:分配並指派
stk->count = 0; stk->head = NULL;
return stk;
}
int Stack_empty(T stk) { assert(stk); return stk->count == 0; }
void Stack_push(T stk, void *x) {
assert(stk);
struct elem *t; NEW(t);
t->x = x; t->link = stk->head; stk->head = t; stk->count++;
}
void *Stack_pop(T stk) {
assert(stk && stk->count > 0);
struct elem *t = stk->head;
stk->head = t->link; stk->count--;
void *x = t->x; FREE(t); return x; // FREE 釋放並置 NULL
}
void Stack_free(T *stk) {
assert(stk && *stk);
for (struct elem *t = (*stk)->head, *u; t; t = u) {
u = t->link; FREE(t);
}
FREE(*stk);
}
typedef struct T *T;,實作定義 struct T,客戶端完全看不見內部欄位。assert 捕捉空指標、前置條件違反,屬可檢查執行期錯誤。NEW/FREE 巨集封裝分配/釋放邏輯,實作與介面解耦。void* 儲存任意型別資料,配合函式指標可擴展為型別安全容器。