標籤:
GCC編譯器(GNU C Compiler)是GNU組織的一款開源 編譯器,它是Linux環境下的預設C語言編譯器。它處理能夠高效的編譯C語言以外,還可以編譯其他語言。並且,現在的GCC已經不光包括編譯器本身,還包含了編譯過程中的工具鏈。
1 GCC編譯流程
在學習使用GCC編譯器之前,首先要知道編譯C程式的基本流程,一般情況下分為下面四步:
(1) 對C語言進行預先處理,產生*.i檔案。
(2) 將上一步產生的*.i檔案編譯產生組合語言檔案,尾碼名為*.s
(3) 將組合語言檔案*.s經過彙編,產生目標檔案,尾碼名為*.o
(4) 將各個模組的*.o檔案連結起來,產生最終的可執行檔
2 GCC常用選項
GCC的編譯選項非常多,現在有上千個,但是我們常用的並不多,下面我們只介紹其中非常實用的幾個。
在這之前,我們先編寫下面的幾個源檔案,以備測試只用。
1 //main.c 2 #include <stdio.h> 3 4 extern int add(int a, int b); 5 extern int mul(int a, int b); 6 7 int main(void) 8 { 9 int a = 10, b = 5;10 int result;11 12 result = add(a, mul(a, b));13 printf("result = %d\n", result);14 return 0;15 }main.c
1 //test1.c2 int add(int a, int b)3 {4 return a+b;5 }test1.c
1 //test2.c2 int mul(int a, int b)3 {4 return a*b;5 }test2.c
2.1 -c選項
該選項(小寫c)表示編譯、彙編指定的源檔案,但是不進行連結。該選項的使用方法如下:
gcc -c source.c
也就是在-c選項後面緊跟要編譯、彙編的C源檔案,最終產生與源檔案名稱相同,但是尾碼為*.o結尾的目標檔案。
[email protected]:~/Documents/c_code$ lsmain.c test1.c test2.c[email protected]-machine:~/Documents/c_code$ gcc -c test1.c[email protected]-machine:~/Documents/c_code$ lsmain.c test1.c test1.o test2.c
可以看到,使用-c選項編譯之後產生了對應的*.o目標檔案。當然,你也可以一次性指定多個C源檔案,使用-c選項後,會針對每一個C源檔案產生一個相應的*.o目標檔案。
[email protected]:~/Documents/c_code$ gcc -c test2.c main.c[email protected]-machine:~/Documents/c_code$ lsmain.c main.o test1.c test1.o test2.c test2.o
2.2 -S選項
該選項(大寫S)將C語言源檔案編譯產生組合語言檔案,但是並不彙編該程式。注意:彙編過程的作用是將組合語言檔案編譯成目標檔案*.o,而-S選項的作用是得到組合語言檔案*.s。該選項的使用方法為:
gcc -S source.c
使用該選項,最終產生與源檔案名稱相同,但是尾碼為*.s結尾的組合語言檔案。
[email protected]:~/Documents/c_code$ gcc -S test1.c[email protected]-machine:~/Documents/c_code$ lsmain.c test1.c test1.s test2.c
當然,輸入的源檔案也不止一個,你可以編譯目前的目錄下的所有C語言源檔案:
[email protected]:~/Documents/c_code$ gcc -S *.c[email protected]-machine:~/Documents/c_code$ lsmain.c main.s test1.c test1.s test2.c test2.s
我們也可以查看產生的組合語言代碼:
1 .file "test1.c" 2 .text 3 .globl add 4 .type add, @function 5 add: 6 .LFB0: 7 .cfi_startproc 8 pushl %ebp 9 .cfi_def_cfa_offset 810 .cfi_offset 5, -811 movl %esp, %ebp12 .cfi_def_cfa_register 513 movl 12(%ebp), %eax14 movl 8(%ebp), %edx15 addl %edx, %eax16 popl %ebp17 .cfi_restore 518 .cfi_def_cfa 4, 419 ret20 .cfi_endproc21 .LFE0:22 .size add, .-add23 .ident "GCC: (Ubuntu 4.8.2-19ubuntu1) 4.8.2"24 .section .note.GNU-stack,"",@progbits
test1.s
GCC編譯器入門