# Header檔

## 什麼是 Header (.h) 檔？

Header (.h) 檔是一個專門儲存function、class、structure等等定義的檔案。這讓程式可以先在 Header 檔內定義功能，並在 Source Code (.cpp) 裡實踐. 這樣可以把程式分割成多個檔案，減少每個檔案的行數並增加可維護性。

## 基本範例

```cpp
// library.h
int fibonacci(int n) {
    int s = 0;
    int d = 1;
    for (int i = 0; i < n-1; i++) {
        int tmp = d;
        d = s + d;
        s = tmp;
    }
    return d;
}
```

```cpp
#include "library.h"

// main.cpp
int main() {
    printf("%d\n", fibonacci(5));
    return 0;
}
```

## 分割定義與實踐

假設我們需要一個程式，幫我執行把degree轉radian，或是把任何角度轉換成-180\~180的小計算，但是我又不想讓 .h 檔變很複雜。這時可以用以下的方法

```cpp
// include/utils.h

namespace Utils {
    float deg_to_rad(float degrees);
    float rad_to_deg(float radians);
    float format_angle(float degrees);
}
```

```cpp
// include/main.h

#include "utils.h"
```

```cpp
// src/utils.cpp
#include "main.h"

float Utils::deg_to_rad(float degrees) {
    return degrees * M_PI / 180.0;
}

float Utils::rad_to_deg(float degrees) {
    return degrees * 180.0 / M_PI;
}

float Utils::format_angle(float degrees) {
    int sign = a < 0 ? -1 : 1;
    float positive_a = abs(a);
    float mod = std::fmod(positive_a, 360);
    if (mod <= 180) {
        return sign * mod;
    } 
    else {
        return sign * (mod - 360);
    }
}
```

接下來就可以在任何有 include main.h 的地方使用 Utils 了

```cpp

// main.cpp

void opcontrol() {
    printf("%f\n", Utils::deg_to_rad(180));
}
```


---

# 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://acezxn.gitbook.io/vex-ji-qi-ren-cheng-shi-jiao-xue/ji-chu-jiao-xue/mo-zu-hua/header-dang.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.
