---
# System prepended metadata

title: C語言中的 `inline`
tags: [C]

---

## 淺談 inline

### 甚麼是 inline ?
根據 [C99規格書](https://www.dii.uchile.cl/~daespino/files/Iso_C_1999_definition.pdf) $6.7.4.5
::: info 
A function declared with an inline function specifier is an inline function. The
function specifier may appear more than once; the behavior is the same as if it appeared only once. Making a function an inline function suggests that calls to the function be as fast as possible. The extent to which such suggestions are effective is implementation-defined.
:::

- 可以得知 `inline` 這個 `function specifier` 可以讓 `function call` 的速度加快


### 使用 inline 的風險

- 參考[這篇](https://hackmd.io/@5iODz6_2TQWOK-sMRViU2Q/HJTMu3V5P)文章

如果嘗試編譯以下代碼
```C=
inline int fib(int n) {
    if (n < 2)
        return 1;
    return fib(n - 1) + fib(n - 2);
}

int main() {
    fib(10);
}
```
會出現 undefined reference to `fib'
```bash
/usr/bin/ld: /tmp/ccybgEA9.o: in function `main':
main.c:(.text+0xe): undefined reference to `fib'
collect2: error: ld returned 1 exit status
```

#### 原因分析
根據 [C99規格書](https://www.dii.uchile.cl/~daespino/files/Iso_C_1999_definition.pdf) $6.7.4.6
::: info
For a function with external linkage, the following restrictions apply: If a function is declared with an inline function specifier, then it shall also be defined in the same translation unit. If all of the file scope declarations for a function in a translation unit include the inline function specifier without extern, then the definition in that translation unit is an inline definition. An inline definition does not provide an external definition for the function, and does not forbid an external definition in another translation unit. An inline definition provides an alternative to an external definition, which a translator may use to implement any call to the function in the same translation unit. It is unspecified whether a call to the function uses the inline definition or the external definition.
:::
1. `fib()` 被視為 `inline definition`
2. `inline definition` 並不會提供 `external definition`
3. `function call` 並不限定使用 `inline definition` 或是 `external definition`
4. 當 `main()` 裡面的 `fib()` 被使用 `external definition` 作為 `function call` 時，linker 找不到 definition，便報錯 `undefined reference to fib`


