Header檔
什麼是 Header (.h) 檔?
Header (.h) 檔是一個專門儲存function、class、structure等等定義的檔案。這讓程式可以先在 Header 檔內定義功能,並在 Source Code (.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;
}#include "library.h"
// main.cpp
int main() {
printf("%d\n", fibonacci(5));
return 0;
}分割定義與實踐
假設我們需要一個程式,幫我執行把degree轉radian,或是把任何角度轉換成-180~180的小計算,但是我又不想讓 .h 檔變很複雜。這時可以用以下的方法
接下來就可以在任何有 include main.h 的地方使用 Utils 了
Last updated