//头文件可能被包含两次:直接包含一次,
//又通过另一个头文件包含一次。
//保护机制只让其文本进入一次。
//--- point.h ---
#ifndef POINT_H
#define POINT_H
typedef struct {
int x;
int y;
} Point;
static inline int manhattan(Point p) {
return abs(p.x) + abs(p.y);
}
#endif //POINT_H
//--- 再次出现同一个 point.h,这是第二个 #include 带来的:
//POINT_H 已经定义,所以这段文本被跳过。
//没有保护的话,manhattan 会被定义两次,导致构建错误
#ifndef POINT_H
#define POINT_H
typedef struct {
int x;
int y;
} Point;
static inline int manhattan(Point p) {
return abs(p.x) + abs(p.y);
}
#endif //POINT_H
//大多数编译器也支持更短的 #pragma once,
//但标准里没有它
Point p = {3, -4};
int distance = manhattan(p);
//distance is 7
printf("distance is %d\n", distance);