gcc 全名 GNU Compiler Collection,是一套能編譯多種語言的編譯器。最初它是 C 語言的編譯器(GNU C Compiler),如今除 C 之外還支援 C++、Java、Pascal 等語言,並橫跨多種硬體平台。

這裡的重定位值得多說一句:原始碼中的位址是從 0 開始的相對位址,程式實際載入記憶體時的位址必然不同,撰寫時也無從得知絕對位址,重定位就是把程式碼與變數對應到具體記憶體位址的過程。注意各階段檔案副檔名的變化(.i → .s → .o → 可執行檔),後面的編譯選項正是圍繞這些副檔名設計的。
| 選項 | 作用 |
|---|---|
| -o | 指定輸出的目標檔名 |
| -E | 只跑 C 預編譯器 |
| -S | 編譯後停止,產生 .s 組語檔 |
| -c | 不連結,只編譯並產生目的檔 |
| -Wall | 對可疑語法發出警告 |
| -Idir | 把 dir 加入標頭檔搜尋路徑 |
| -Ldir | 把 dir 加入函式庫搜尋路徑 |
| -llib | 連結 lib 庫 |
| -g | 在目的檔中嵌入除錯資訊,供 gdb 使用 |
有了 hello.c,可以逐階段來:
gcc -E hello.c -o hello.i # 預處理
gcc -S hello.i -o hello.s # 編譯成組語
gcc -c hello.s -o hello.o # 組譯成目的檔
gcc hello.o -o hello # 連結
gcc hello.c -o hello # 一次完成編譯與連結
gcc -c hello.c # 只編譯,產生 hello.o
養成加 -Wall 的習慣很重要。下面這段程式不開警告時編譯毫無異狀,但結果是錯的:
#include <stdio.h>
int main() {
printf("the number is %f ", 5); /* 輸出 0.000000 */
return 0;
}
加上 -Wall(gcc -Wall bad.c -o bad)就會看到:
warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat=]
以 hello.c、hello.h、main.c 三個檔案為例:
/* hello.c */
#include <stdio.h>
#include "hello.h"
void printHello() { printf("hello world!\n"); }
/* main.c */
#include <stdio.h>
#include "hello.h"
int main() { printHello(); return 0; }
/* hello.h —— 只放函式宣告 */
#ifndef _HELLO_
#define _HELLO_
void printHello();
#endif
可以一次編完,也可以分開編譯:
gcc hello.c main.c -o main
gcc -Wall -c main.c -o main.o
gcc -Wall -c hello.c -o hello.o
gcc -Wall main.o hello.o -o main
分開編譯的好處很實際:某個模組改了,只需重編那一支,不必全部重來,大專案能省下大量時間。
C 語言開發時,標頭檔提供常數定義與函式宣告,函式庫則是預先編譯好、依可重用原則撰寫的函式集合。用庫的好處是模組化、可重用、易維護。庫分兩類:
標頭檔與庫的常見位置:/usr/include、/usr/local/include、/usr/lib、/usr/local/lib、/lib 及其子目錄。
ar rcs libhello.a hello.o # rcs = replace and create
使用方式:
gcc -Wall main.c libhello.a -o main
gcc -Wall -L. main.c -o main -lhello /* -lhello 即 libhello */
-L. 表示庫就在目前目錄;若庫在系統目錄則不必加。同理,-I. 用於標頭檔搜尋。
gcc -shared -fPIC hello.o -o libhello.so
gcc -Wall main.o -o main -L. -lhello
指令與靜態庫相同,但當兩者並存時,gcc 優先使用共享庫。-fPIC 表示產生位置無關碼(position independent code),載入位址不固定也能正確運行。
若共享庫不在目前目錄,有三種讓 gcc 找得到它的方法:把 .so 複製到系統庫路徑(一般指 /usr/lib);在 ~/.bash_profile 設定 LD_LIBRARY_PATH;或編輯 /etc/ld.so.conf 後執行 ldconfig 更新快取。
搜尋依序是:先由左至右找 -I 與 -L 指定的目錄;找不到再查環境變數指定的路徑(標頭檔是 C_INCLUDE_PATH,庫是 LIBRARY_PATH);最後才搜系統預設目錄。釐清這個順序,前面 90% 的「找不到標頭檔/找不到庫」錯誤都能自己定位。