一段 C 程式從原始碼到可執行的二進位檔,中間到底經過哪些步驟?本文以 Linux 下的 C 語言編譯流程為例逐步拆解。
先寫最經典的範例:
// hello.c
#include <stdio.h>
int main() {
printf("hello world!\n");
}
編譯與執行只需兩行:
$ gcc hello.c # 編譯 $ ./a.out # 執行,輸出 hello world!
熟悉到讓人以為編譯是件再簡單不過的事。真的如此嗎?事實上,gcc 這一行命令背後依序執行了四個階段:
為了後續說明方便,準備一個稍複雜的結構:自訂頭檔 mymath.h,實作放在 mymath.c,再由 test.c 使用。
├── test.c
└── inc
├── mymath.h
└── mymath.c
// test.c
#include <stdio.h>
#include "mymath.h" // 自訂頭檔
int main() {
int a = 2;
int b = 3;
int sum = add(a, b);
printf("a=%d, b=%d, a+b=%d\n", a, b, sum);
}
// mymath.h #ifndef MYMATH_H #define MYMATH_H int add(int a, int b); int sub(int a, int b); #endif
// mymath.c
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
預處理會把所有 #include 的標頭檔內容與巨集定義,替換成真正的內容,結果仍是純文字檔,只是體積暴增。gcc 的預處理由 cpp 完成:
$ gcc -E -I./inc test.c -o test.i # 或直接呼叫 $ cpp test.c -I./inc -o test.i
參數說明:-E 表示預處理後即停止;-I 指定標頭檔目錄;-o 指定輸出檔名。
前後對比相當明顯:
test.c,146 B,9 行test.i,17691 B,857 行這裡的 test.i 依然是文字檔,用任何編輯器都能打開。
這裡的「編譯」不是指整個原始碼到二進位的過程,而是狹義地指把預處理後的程式轉換成特定平台的組語程式碼:
$ gcc -S -I./inc test.c -o test.s
-S 表示編譯後停止。輸出的 test.s 是組語,同樣是文字檔:
.file "test.c"
.section .rodata
.LC0:
.string "a=%d, b=%d, a+b=%d\n"
.text
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
andl $-16, %esp
subl $32, %esp
movl $2, 20(%esp)
movl $3, 24(%esp)
movl 24(%esp), %eax
movl %eax, 4(%esp)
movl 20(%esp), %eax
movl %eax, (%esp)
call add
movl %eax, 28(%esp)
...
call printf
leave
ret
初次看到這一大片暫存器搬運,不必急著讀懂——多數應用開發者一輩子也不會直接寫組語。
組譯把上一步的組語翻成機器碼,產出的檔案稱為目的檔(object file),是二進位格式。gcc 內部透過 as 完成:
$ as test.s -o test.o # 等價寫法 $ gcc -c test.s -o test.o
每個原始檔都會產生一個對應的目的檔,因此 mymath.c 也要產出 mymath.o。
連結把多個目的檔與所需的函式庫(.so 等)組裝成最終的可執行檔:
$ ld -o test.out test.o inc/mymath.o ...libraries...
這一步才真正把 test.o 裡對 add 的呼叫,與 mymath.o 中的實作綁在一起;標準庫如 printf 也是在這裡被拉進來。
可見編譯一點都不單純,而是預處理、編譯、組譯、連結四段接力。平常我們用 gcc 時不必關心中間產物,但這幾步從未缺席。當然,也不需要為流程繁瑣而煩惱,你依然可以:
$ gcc hello.c $ ./a.out
理解這四個階段最大的好處在除錯:連結錯誤多半是符號找不到(某個目的檔沒被加入),標頭檔相關的怪異錯誤往往出在預處理,而最佳化與平台相依問題通常落在編譯階段。知道問題在哪一層,排查就快得多。