Ubuntu//gcc小筆記

  1. Ubuntu//gcc小筆記

Ubuntu//gcc小筆記

原文連結: https://darkblack01.blogspot.com/2013/05/ubuntugcc.html
移植時的最後更新日期: 2013-05-20T09:52:17.311+08:00

                main.c  →  main.s  →  main.o   →  main
source code  →  assembly file  →  object file  →  binary file

source code: 文字檔,就是程式碼本身
assembly file: 組合語言檔,組合語言程式碼
object file: 二進制的檔案,不可以單獨執行
binary file: 二進制檔案,執行檔

$ gcc main.c
產生一個預設檔名(a.out)的binary檔

$ gcc -c main.c
產生一個和main.c同名的main.o檔

$ gcc -o main man.c
產生一個main的binary檔

$ gcc -S main.c
產生一個main.s的組合語言檔

$ gcc -E main.c
顯示預處理器加的+你自己打的程式碼,不產生任何檔案

$ gcc -O main.c
速度最佳化,產生a.out(同gcc main.c)

Sample code:

//hello.c
#include <stdio .h>

void hello()
{
printf(“hello function”);
}
//main.c
#include <stdio .h>

int main()
{
hello(); //call hello function in hello.c
printf(“hello main”);

return 0;
}
$ gcc -c hello.c
$ gcc -c main.c
處理.c檔,產生hello.o和main.o檔(各別將兩個檔案編譯好)

$ gcc -o main main.o hello.o
處理.o檔,組合main.o和hello.o檔,並產生main的binary檔


加入函式庫
$ gcc -c main.c -l -L/(path)
-l: 要加入lib (*.so 動態函式庫, *.a 靜態函式庫)
-L: 加入的lib路徑在哪

找#include <xxx.h>的路徑
$ gcc -c main.c
main.c:3:20: 嚴重錯誤: **.h:沒有此一檔案或目錄
編譯插斷。
這種情況是你加入的
.h檔找不到,也就是要給予該檔的路徑
$ gcc -c main.c -I/(path)
-I加入include的搜尋.h檔的路徑


參考資料
[1] $man gcc
[2] gcc 參數 備註
[3] 鳥哥的 Linux 私房菜 – 使用傳統程式語言進行編譯的簡單範例
[4] GCC常用編譯參數  ←簡單易懂
[5] GCC使用簡介
[6] 鳥哥的 Linux 私房菜 – 函式庫管理