# 連結錯誤

最後把目標檔統整交給連結器的時候，必須剛好包含構成程式整體所需的資訊。

如果程式只有`foo`函式的宣告但是並沒有定義的時候，特別C檔案包含呼叫`foo`都可以正常編譯成功。但是，最後連結器想要製作完整程式的時候，在要修正`foo`呼叫位址的地方，因為沒有`foo`所以無法修正，就會報錯。

連結時發生的錯誤就稱為連結錯誤。

複數的目標檔包含同一個函式時也會發生連結錯誤。對連結器來說，有重複的時候會不知道要選哪一個。像這類重複錯誤，很常在不小心把定義寫在標頭檔時發生。標頭檔會被複數的C檔案所引入，所以標頭檔有定義的話，就形同於重複在複數個C檔案裡寫定義的狀況。為了排除這種錯誤，請只在標頭檔寫宣告，本體請移到某個C檔案裡。

{% hint style="info" %}

## 小知識：重複定義與連結錯誤

發生重複定義時，連結器也可以選擇某一個定義而忽略剩下的定義。這類連結器中重複定義也不會報錯。

實際上的目標檔中，有的可以讓使用者選擇要不要允許重複的定義，還有的是像行內函數（inline function）或C++模板展開的結果等，允許重複的目標檔。目標檔的格式和連結器的做法其實比想像中還複雜，例外也很多，但那些充其量也只是例外。基本上，重複的定義一般來說還是被視為錯誤的。
{% endhint %}


---

# 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://koshizuow.gitbook.io/compilerbook/separate_compile_linking/separate_compilation/link_error.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.
