สร้าง Header File เองได้หรือไม่?
ได้ สร้างไฟล์ .h ใส่ function prototype, global variable, struct แล้ว #include "filename.h"
ขั้นตอน
- สร้าง
swapping.hใส่ฟังก์ชัน swap - ใน
main.cใช้#include "swapping.h"(เครื่องหมายคำพูดไม่ใช่ <>) - ทั้งสองไฟล์ต้องอยู่โฟลเดอร์เดียวกัน
ตัวอย่าง
main.c
#include <stdio.h>
#include "swapping.h"
void main() {
int a = 40, b = 60;
swapping(&a, &b);
printf("a = %d\n", a);
printf("b = %d\n", b);
}
swapping.h
void swapping(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
ข้อสังเกต
- Header file นามสกุล .h
- อยู่โฟลเดอร์เดียวกับ .c
- ใช้ #include "file.h" สำหรับ custom header