GCC編譯過程的4個階段

2021-08-30 17:18:30 字數 2557 閱讀 3869

在使用gcc編譯程式時,其編譯過程可以分為4個階段:預處理(pre-processing) -> 編譯(compling) -> 彙編(assembling) -> 連線(linking)

.程式設計師完全可以根據自己的需要讓gcc在編譯的任何乙個階段結束,檢查活使用編譯起在該階段輸出的資訊,或者對其生成的二進位制檔案進行控制。

我想通過乙個hello world程式對gcc的編譯過程有進一步的認識。

[xredman@localhost demo]$ cat test.c

#include int main(void)

首先來個一步到位編譯成可執行檔案

[xredman@localhost demo]$ gcc -wall test.c -o test.o

[xredman@localhost demo]$ ./test.o

hello world

ok,這是我日常生活中所用的,以下將分步驟演示

a.預處理(pr-processing)

gcc -e test.c -o test.i
開啟test.i檔案,嚇我嘛,編譯器原來為我們做了這麼多事,辛苦了。這裡主要負責展開在原始檔中定義的巨集,並向其中插入#include語句所包含的內容

# 1 "test.c"

# 1 ""

# 1 ""

# 1 "test.c"

# 1 "/usr/include/stdio.h" 1 3 4

# 28 "/usr/include/stdio.h" 3 4

# 1 "/usr/include/features.h" 1 3 4

# 329 "/usr/include/features.h" 3 4

# 1 "/usr/include/sys/cdefs.h" 1 3 4

# 313 "/usr/include/sys/cdefs.h" 3 4

# 1 "/usr/include/bits/wordsize.h" 1 3 4

# 314 "/usr/include/sys/cdefs.h" 2 3 4

# 330 "/usr/include/features.h" 2 3 4

# 352 "/usr/include/features.h" 3 4

# 1 "/usr/include/gnu/stubs.h" 1 3 4

# 1 "/usr/include/bits/wordsize.h" 1 3 4

# 5 "/usr/include/gnu/stubs.h" 2 3 4

# 1 "/usr/include/gnu/stubs-32.h" 1 3 4

....

b.編譯(compiling)

[xredman@localhost demo]$ gcc -s test.i -o test.s
編譯之後應該就是匯程式設計序了吧,檢視內容如下

[xredman@localhost demo]$ cat test.s

.file "test.c"

.section .rodata

.lc0:

.string "hello world"

.text

.globl main

.type main, @function

main:

leal 4(%esp), %ecx

andl $-16, %esp

pushl -4(%ecx)

pushl %ebp

movl %esp, %ebp

pushl %ecx

subl $4, %esp

movl $.lc0, (%esp)

call puts

movl $0, %eax

addl $4, %esp

popl %ecx

popl %ebp

leal -4(%ecx), %esp

ret.size main, .-main

.ident "gcc: (gnu) 4.1.2 20080704 (red hat 4.1.2-48)"

.section .note.gnu-stack,"",@progbits

c.彙編(assembling)

彙編這一步是將匯程式設計序翻譯成機器碼,這也就決定了生成的程式能執行在哪種平台下,傳說中gcc將呼叫gas彙編器

[xredman@localhost demo]$ gcc -c test.s -o test.o
d.連線(linking)

這是最後一步,將生成的目標檔案和其所依賴的庫檔案進行連線,生成乙個可執行檔案。

[xredman@localhost demo]$ gcc test.o -o test

[xredman@localhost demo]$ ./test

hello world

ok,練習完畢,我已經知道gcc的基本工作過程了。

gcc編譯的四個階段

gcc編譯的四個階段 如下圖 e preprocess only do not compile,assemble or link 只預處理,不會編譯 彙編 鏈結 s compile only do not assemble or link 只編譯,不會彙編 鏈結 c compile and asse...

GCC編譯的四個階段

gcc編譯流程分為4個步驟,分別為 預處理 pre processing 編譯 compiling 彙編 assembling 鏈結 linking 1 預處理階段 在該階段,編譯器將上述 中的stdio.h編譯進來,並且使用者可以使用gcc的選項 e 進行檢視,該選項的作用是把源 進行預處理。預處...

gcc編譯幾個階段

正文 編譯流程分析 編譯分為幾個過程 a 預處理 b 編譯 c 彙編 d 鏈結 以下分析,如何處理各個階段 首先預處理階段 目的就是要使include之中的內容編譯進去。並且用 e命令作用是進行檢視。作用是gcc的預處理過程結束後停止編譯 gcc指令的一般格式為 gcc 選項 要編譯的檔案 選項 目...