ANSI 標準規定的預處理指令均以 # 開頭。本節介紹常用指令。
#define 宏名 替換字符串(或數值)
編譯時將宏名替換為定義內容。慣例用大寫,放在程序開頭,無分號。
#define TRUE 1
#define FALSE 0
#define MAX(x,y) ((x>y)?x:y)
#define MIN(x,y) ((x<y)?x:y)
帶參數宏調用時實參替換形參。
#error 出錯信息
編譯遇到此指令即停止,顯示 Fatal: filename linename error directive,用於調試。
#include <stdio.h> // 系統頭文件,按環境路徑查找
#include "myheader.h" // 用戶文件,先按當前目錄查找
可嵌入任意文件,甚至在函數體中:
main() {
#include "help.c" // help.c 內容: printf("Glad to meet you here!");
}
#define MAX 200
main() {
#if MAX > 999
printf("compiled for bigger\n");
#else
printf("compiled for small\n");
#endif
}
若常數表達式為真編譯 #if-#else 間代碼,否則編譯 #else-#endif 間代碼。
#define TRUE 1
...
#undef TRUE
使宏定義僅在需要的程序段生效。