#include 的作用是「把一個檔案的全部內容複製到另一個檔案中」,屬於預處理階段的工作。
1. #include <檔名>
直接到 C 語言標準函式庫的標頭檔所在目錄中尋找檔案。
2. #include "檔名"
系統會先在原始碼目前的目錄下尋找,找不到再到作業系統的 path 路徑中查找,最後才到標準函式庫標頭檔的目錄。
#include 允許巢狀包含,例如 a.h 包含 b.h、b.h 包含 c.h;但不允許遞迴包含,例如 a.h 包含 b.h,而 b.h 又包含 a.h,這樣會造成無限展開。
第一組:lisi.h 與對應的 .c
// lisi.h
#ifndef LISI_H
#define LISI_H
int sum(int a, int b);
#endif
// lisi.c
int sum(int a, int b) {
return a + b;
}
第二組:wangwu.h 與主程式
// wangwu.h
#ifndef WANGWU_H
#define WANGWU_H
int minus(int a, int b);
#endif
/*
1. <> 表示系統內建的檔案," " 表示自訂的檔案
2. 不允許循環包含,例如 a.h 包含 b.h,b.h 又包含 a.h
*/
#include "lisi.h"
#include "wangwu.h"
#include <stdio.h>
int main()
{
int c = sum(10, 19);
printf("c is %d\n", c);
return 0;
}
標頭檔上方的 #ifndef / #define / #endif 組合稱為「標頭保護(header guard)」,作用是避免同一個標頭檔在同一個編譯單元中被重複展開。在 C 語言中這是必要的習慣,因為 #include 不像 Objective-C 的 #import 那樣自動去重。命名上通常直接用檔名大寫加上底線,例如 LISI_H,只要同一專案內不重複即可。