Header File (ไฟล์ส่วนหัว) ในภาษา C ช่วยให้เราสามารถนำโค้ดที่ใช้ซ้ำไปใช้ในหลายไฟล์ได้ โดยแยก Declaration (การประกาศ) ออกจาก Implementation (การนำไปใช้งาน) ทำให้โค้ดมีโครงสร้างดีขึ้น และง่ายต่อการบำรุงรักษา
ขั้นตอนการสร้าง Header File
- สร้างไฟล์ใหม่ด้วยนามสกุล .h (เช่น
my_header.h) - วาง Function Prototypes, Constants, Macros, Struct Definitions หรือ Global Variables (ด้วย
extern) - ไม่ควร มีฟังก์ชัน
main()ใน Header File - วางไฟล์ .h ไว้ในโฟลเดอร์เดียวกับไฟล์ .c ที่จะใช้งาน
- Include ด้วยเครื่องหมายคำพูดคู่:
#include "my_header.h"
ตัวอย่าง: ไฟล์ my_header.h
// my_header.h #ifndef MY_HEADER_H #define MY_HEADER_H // Constant #define MY_VAR 10 // Function Prototypes int add(int x, int y); int sub(int x, int y); int mul(int x, int y); int negate(int x); #endif // MY_HEADER_H
หมายเหตุ: ควรใช้ Include Guards (#ifndef, #define, #endif) เพื่อป้องกันการ Include ซ้ำซ้อน
ตัวอย่าง: ไฟล์ my_header.c (Implementation)
// my_header.c
#include "my_header.h"
int add(int x, int y) { return x + y; }
int sub(int x, int y) { return x - y; }
int mul(int x, int y) { return x * y; }
int negate(int x) { return -x; }
ตัวอย่าง: ไฟล์ main.c (การใช้งาน)
#include <stdio.h>
#include "my_header.h"
int main(void) {
printf("The value of MY_VAR: %d\n", MY_VAR);
printf("The value of (50 + 84): %d\n", add(50, 84));
printf("The value of (65 - 23): %d\n", sub(65, 23));
printf("The value of (3 * 15): %d\n", mul(3, 15));
printf("The negative of 15: %d\n", negate(15));
return 0;
}
ผลลัพธ์
The value of MY_VAR: 10 The value of (50 + 84): 134 The value of (65 - 23): 42 The value of (3 * 15): 45 The negative of 15: -15
วิธีคอมไพล์หลายไฟล์พร้อมกัน
gcc main.c my_header.c -o my_program ./my_program
Best Practices
- แยก Declaration (.h) และ Definition (.c) ชัดเจน
- ใช้ Include Guards ทุกครั้ง
- หลีกเลี่ยง Global Variables ใน Header (ถ้าจำเป็นต้องใช้
extern) - Document ฟังก์ชันด้วย Comments
- จัดกลุ่มฟังก์ชันที่เกี่ยวข้องใน Header เดียวกัน