從c/c++源文件,到可以執行文件,需要以下幾個步驟:
- 預處理/編譯
- 匯編
- 鏈接

下面我們以hello world程序為例,展示整個編譯鏈接過程。
1. 編寫hello.c代碼
#include <stdio.h> int main(void) { printf("Hello World!\n"); return 0; }
2.使用gcc –E hello.c –o hello.i, 將源文件hello.c文件預處理生成hello.i
3.編譯, gcc –S hello.i –o hello.s, 生成匯編程序hello.s,對於x86系統,生成x86匯編代碼。
ction .rodata .LC0: .string "Hello World!" .text .globl main .type main, @function main: .LFB0: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 leaq .LC0(%rip), %rdi call puts@PLT movl $0, %eax popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE0: .size main, .-main .ident "GCC: (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0" .section .note.GNU-stack,"",@progbits
4.匯編 gcc –c hello.s –o hello.o, 生成目標機器碼。
5.鏈接,和系統庫文件進行鏈接,ld hello.o –o hello, 執行會出錯,只靠一個hello.o不能生成一個完整的可執行文件。
gcc hello.c –o hello 可以直接生成可執行文件。