Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

GCC/G++ 常用編譯命令與調試入門

先從一組典型的 g++ 用法看起:

g++ test.cpp main.cpp -o main      # 生成可執行的 main
g++ -c -fPIC -o test.o test.cpp    # 生成目標檔 test.o
g++ -shared -o libCompute.so test.o # 生成 SO 共享庫
g++ main.cpp -L. -lCompute -o somain # 連結動態庫,-L 指定查找路徑

其中 -lCompute 遵循命名規則:編譯器會在名字前加 lib、後加 .so,因此它實際查找的是 libCompute.so。

一、常用編譯選項(以 test.c 為例)

gcc test.c:預處理、匯編、編譯並連結,預設輸出 a.out。

gcc test.c -o test:以 -o 指定輸出檔名為 test。

gcc -E test.c -o test.i:僅做預處理,輸出 test.i。

gcc -S test.i:將預處理結果匯編為 test.s。

gcc -c test.s:編譯為目標檔 test.o。

gcc test.o -o test:將目標檔連結為最終可執行檔。

gcc -O1 test.c -o test:以優化等級 1 編譯,等級 1~3 越大優化越強、編譯越慢。

二、多源檔編譯

方法一,一次編譯全部:gcc testfun.c test.c -o test。方法二,先分別編譯再連結:

gcc -c testfun.c
gcc -c test.c
gcc -o test testfun.o test.o

兩者相比,方法二只需重新編譯被修改的檔案,適合大型專案。若檔案眾多,則應把編譯過程寫進 makefile。

三、Makefile 範例

MyFirst: MyFirst.o hello.o
    g++ MyFirst.o hello.o -o MyFirst
Hello.o: Hello.cpp
    g++ -c Hello.cpp -o Hello.o
MyFirst.o: MyFirst.cpp
    g++ -c MyFirst.cpp -o MyFirst.o

編寫規則:以「#」開頭為註解;依賴關係寫成 target: components 再加規則。存檔後執行 make MyFirst 即可。

四、用 gdb 調試

編譯時加上 -g 參數以保留除錯資訊:g++ -g hello.cpp -o hello,再以 gdb ./hello 啟動。常用命令有:

list <行號>     顯示原始碼
break <行號>    設定中斷點
run            執行
continue       從中斷點繼續
print <變數>    查看變數值
del <行號>      刪除中斷點
step           單步執行(可進入函數)
next           單步執行(不進入函數)
quit           退出

由於手寫的 makefile 未必能跨平台通用,實務中常見以 automake/autoconf 或 CMake 等工具來生成,值得進一步學習。

Copyright © Linux教程網 All Rights Reserved