Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Custom Header Files ในภาษา C: สร้างและใช้ Header ไฟล์เอง

สร้าง Header File เองได้หรือไม่?

ได้ สร้างไฟล์ .h ใส่ function prototype, global variable, struct แล้ว #include "filename.h"

ขั้นตอน

  1. สร้าง swapping.h ใส่ฟังก์ชัน swap
  2. ใน main.c ใช้ #include "swapping.h" (เครื่องหมายคำพูดไม่ใช่ <>)
  3. ทั้งสองไฟล์ต้องอยู่โฟลเดอร์เดียวกัน

ตัวอย่าง

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