C 語言中以 `#` 開頭的行稱為編譯預處理命令。主要命令:`#define`, `#undef`, `#include`, `#if`, `#else`, `#elif`, `#endif`, `#ifdef`, `#ifndef`, `#line`, `#pragma`, `#error`。預處理在編譯前執行,進行文本替換、文件包含、條件編譯等。
#define 宏名 替換文本
#define 宏名(形參表) 替換文本
#undef 宏名
使宏定義在該行後失效。作用域從 `#define` 到 `#undef` 或文件結尾。
#include "文件名" // 先在源文件目錄查找,再按系統路徑 #include <文件名> // 直接按系統標準路徑查找
#if 常量表達式 #elif 常量表達式 #else #endif #ifdef 宏名 // 等價 #if defined(宏名) #ifndef 宏名 // 等價 #if !defined(宏名)
常用於:跨平台代碼隔離、防止頭文件重複包含(`#ifndef HEADER_H #define HEADER_H ... #endif`)、調試開關。
#include <stdio.h>
// 宏定義判斷輸入字符是否為字母
#define MYALPHA(c) (((c) >= 'A' && (c) <= 'Z') || ((c) >= 'a' && (c) <= 'z') ? 1 : 0)
int main() {
char ch;
printf("Please enter a character 'c'.\n");
printf("Enter 'f' or 'F' to finish.\n");
// scanf("%c%*c", &ch) 讀取字符並跳過換行符
while (scanf("%c%*c", &ch) == 1 && ch != 'f' && ch != 'F') {
printf("The ASCII code of character is: %d\n", ch);
if (MYALPHA(ch))
printf("c is a character.\n");
else
printf("c is not a character.\n");
}
return 0;
}
#undef MYALPHA // 終止宏作用域
編譯器內建宏:`__FILE__`(當前文件名)、`__LINE__`(當前行號)、`__DATE__`(編譯日期)、`__TIME__`(編譯時間)、`__STDC__`(標準 C 標識)。常用於調試日志。