上回在 VC6.0 成功跑通 Hello World,但編譯、鏈接全由 IDE 自動完成,雖方便卻不清楚內部步驟,知識不屬於自己。決定用記事本寫程式,親手實現編譯、鏈接全過程。
#include <stdio.h>
int main(void)
{
printf("Hello,World! ");
return (0);
}
存為 hello.c。
CMD 執行 CL hello.c,生成兩個文件:hello.exe(Windows 可執行檔)與 hello.obj(目標檔,COFF 格式,跨平台交互用)。為何一次出兩個?因 CL 默認自動鏈接。
/c 參數加上 /c 後,只生成 .obj。此時無 .exe,如何生成?需鏈接器 link:
link hello.obj
為 Win 平台產生 PE 格式 hello.exe,可直接執行!
#include 展開過程網友提醒 #include <stdio.h> 會原樣展開文件內容。用 CL /c /P hello.c 生成 .i 文件,打開竟有 400 多行!對照 stdio.h 發現:stdio.h 內部又包含其他頭文件,全展開後自然龐大。
現在大致明白第一個程式如何從源碼變成可執行檔了。