CC Lab
หลักสูตรการเขียนโปรแกรมภาษา C
ความคืบหน้าเก็บไว้ในเบราว์เซอร์นี้โหมดผู้เรียน
บทเรียน / หลายไฟล์และเฮดเดอร์ / 01

ไฟล์ต้นฉบับ .c

อธิบายหน้าที่ของ main.c, header และ implementation file ในโปรเจกต์หลายไฟล์ได้

แนวคิดและการทดลองประมาณ 15 นาที
บทที่ 1 จาก 7
แนวคิดหลัก

header ประกาศ interface เช่น function prototype; ไฟล์ .c แต่ละไฟล์เป็น translation unit ของตัวเอง Compiler แปล .c เป็น object แล้ว linker เชื่อม symbol ที่ตรงกันเข้าด้วยกัน

ลงมือสำรวจ

เปลี่ยนค่าและสังเกตผล
Project file tree
root/ grade-project├ main.c├ grade.c└ grade.h
main.c → #include "grade.h" · grade.c → implement grade_from_score · linker รวม object files

อ่านโค้ดตัวอย่าง

#include <stdio.h>
int grade_from_score(int score);
int main(void) {
    printf("%d\n", grade_from_score(85));
    return 0;
}
int grade_from_score(int score) { return score >= 50 ? 1 : 0; }

ทำนายผลก่อนทดลอง

Prediction

ควรส่งไฟล์ .h ให้ GCC compile เป็น source แยกหรือไม่?

main.c · แยก prototype ไป grade.h และ implementation ไป grade.c
กำลังโหลดตัวแก้ไขโค้ด…

บันทึกโค้ดไว้ใน localStorage ของเบราว์เซอร์นี้ หากเปิดใช้งานการรัน โค้ดและ stdin จะถูกส่งไปยัง Wandbox

จบบทเรียน

กลับไปยังโมดูลบทถัดไป