以最經典的 helloworld 為例:
#include <stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}
gcc 的編譯過程可細分為四個階段:預處理、編譯、組譯、連結。
由於用到了 stdio.h,gcc 首先要把標頭檔內容展開到源碼前面:
gcc -E helloworld.c -o helloworld.i
-E 表示只做預處理,-o 指定輸出檔名。產生的 helloworld.i 有上百行,末尾大致如下:
extern int fileno_unlocked (FILE *__stream) __attribute__ ((__nothrow__)) ;
# 774 "/usr/include/stdio.h" 3 4
extern FILE *popen (__const char *__command, __const char *__modes) ;
extern int pclose (FILE *__stream);
# 2 "helloworld.c" 2
int main()
{
printf("Hello World\n");
return 0;
}
除了標頭檔展開,預處理階段還負責巨集替換與條件編譯。
這一階段進行語法檢查與分析,把 C 轉成組語:
gcc -S helloworld.i -o helloworld.s
-S 表示只編譯不組譯,輸出 helloworld.s。
把組語翻成 CPU 能讀的二進位目標檔:
gcc -c helloworld.s -o helloworld.o
-c 表示只組譯不連結。
目標檔雖然機器看得懂,卻通常無法直接執行。一個程式往往由多個源檔組成,每個源檔對應一個目標檔;而 helloworld.c 用到了 stdio.h 對應的函式庫,必須把目標檔與函式庫連結起來才能運行。連結就是把所有目標檔與所需函式庫湊在一起,產出最終的可執行檔。
依連結方式不同,函式庫分為靜態庫與動態庫兩種,這部分的生成與差異留待後續說明。