# GCC 編譯器

## GCC 編譯器

<https://gcc.gnu.org/>

一般常用方法

```
gcc test.c -o test && ./test
```

## 一. 常用編譯命令選項

假設欲編譯程式為 test.c。

**1. 無選項編譯鏈接**  <br>

用法：`gcc test.c`

作用：將test.c預處理、匯編、編譯並鏈接形成可執行文件。這裏未指定輸出文件，默認輸出為a.out。

**2. 選項 -o**  <br>

用法：`gcc test.c -o test`

作用：將test.c預處理、匯編、編譯並鏈接形成可執行文件test。-o選項用來指定輸出文件的文件名。

**3. 選項 -E**  <br>

用法：`gcc -E test.c -o test.i`

作用：將test.c預處理輸出test.i文件。

**4. 選項 -S**  <br>

用法：`gcc -S test.i`

作用：將預處理輸出文件test.i匯編成test.s文件。

**5. 選項 -c**  <br>

用法：`gcc -c test.s`

作用：將匯編輸出文件test.s編譯輸出test.o文件。

**6. 無選項鏈接**  <br>

用法：`gcc test.o -o test`

作用：將編譯輸出文件test.o鏈接成最終可執行文件test。

**7. 選項-O**  <br>

用法：`gcc -O1 test.c -o test`

作用：使用編譯優化級別1編譯程序。級別為1\~3，級別越大優化效果越好，但編譯時間越長。

## 二. 多源文件的編譯方法

如果有多個源文件，基本上有兩種編譯方法：

> 假設有兩個源文件為test.c和testfun.c

**1. 多個文件一起編譯**

用法：`gcc testfun.c test.c -o test`

作用：將testfun.c和test.c分別編譯後鏈接成test可執行文件。

**2. 分別編譯各個源文件，之後對編譯後輸出的目標文件鏈接。**  <br>

用法：

`gcc -c testfun.c` // 將testfun.c編譯成testfun.o

`gcc -c test.c` // 將test.c編譯成test.o

`gcc -o testfun.o test.o -o test` // 將testfun.o和test.o鏈接成test

以上兩種方法相比較，第一中方法編譯時需要所有文件重新編譯，而第二種方法可以只重新編譯修改的文件，未修改的文件不用重新編譯。

參考 :

<http://developer.51cto.com/art/200810/94747.htm>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://easonwang.gitbook.io/c/chapter1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
