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

4 ขั้นตอนแปลงโปรแกรม C เป็น Machine Code


กระบวนการสร้างและรันโปรแกรม C

โปรแกรม C ต้องผ่าน **4 ขั้นตอน** เพื่อกลายเป็น Executable Machine Code

ขั้นตอนที่ 1: Writing & Editing (เขียนและแก้ไข)

  • ใช้ **Text Editor** (VS Code, Vim, Notepad++, Code::Blocks, v.v.)
  • เขียน Source Code บันทึกเป็น .c file (Source File)
  • ไฟล์นี้เป็น Input ให้ Compiler

ขั้นตอนที่ 2: Compiling (คอมไพล์)

Compiler แปลง Source Code → Machine Language แบ่ง 2 ส่วนย่อย:

2.1 Preprocessor (ก่อนคอมไพล์)

  • อ่าน Source Code จัดการ Preprocessor Directives (ขึ้นต้นด้วย #)
  • #include - นำไฟล์ Header มาต่อ
  • #define - Macro Substitution
  • #ifdef/#endif - Conditional Compilation
  • Output: **Translation Unit** (ไฟล์ .i)

2.2 Translator (คอมไพเลอร์จริง)

  • แปลง Translation Unit → **Assembly Code**
  • ต่อมา Assembly → **Object Code** (Machine Code + Relocation Info)
  • Output: **Object File** (.o หรือ .obj)
  • ยัง **ไม่ใช่ Executable** (ขาด Library Functions)

ขั้นตอนที่ 3: Linking (ลิงก์)

  • Linker** รวม Object File กับ **Library Functions** (printf, scanf, malloc, etc.)
  • Resolve Symbol Addresses (Function Calls, Global Variables)
  • Output: **Executable File** (.exe Windows, a.out Linux, no extension macOS)
  • 2 ประเภท:
    • Static Linking: Library Code คัดลอกเข้า Executable (ใหญ่, เร็ว, Standalone)
    • Dynamic Linking: ใช้ Shared Library (.dll, .so) รันตอน Execute (เล็ก, ต้องมี Library บนเครื่อง)

ขั้นตอนที่ 4: Executing (รันโปรแกรม)

  • Loader** โหลด Executable เข้า **RAM (Memory)**
  • จัดสรร Memory Segments: Text, Data, BSS, Heap, Stack
  • ตั้งค่า Registers, Stack Pointer, Program Counter
  • โปรแกรมเริ่มทำงานที่ main()
  • อ่าน Input → Process → Output

ภาพรวมกระบวนการ

Source (.c)
    │
    ▼ Preprocessor (#include, #define)
Translation Unit (.i)
    │
    ▼ Compiler (Translator)
Assembly (.s) → Object File (.o/.obj)
    │
    ▼ Linker (+ Libraries)
Executable (.exe / a.out)
    │
    ▼ Loader
Running Process (ใน RAM)

คำสั่ง GCC แบบแยกขั้นตอน


# 1. Preprocess only
gcc -E hello.c -o hello.i

# 2. Compile to Assembly
gcc -S hello.i -o hello.s

# 3. Assemble to Object
gcc -c hello.s -o hello.o

# 4. Link to Executable
gcc hello.o -o hello

# หรือ One-shot (ปกติ)
gcc hello.c -o hello

ตัวอย่างโปรแกรม: หาค่าเฉลี่ย 3 จำนวน


#include 

int main() {
    int a, b, c, sum;
    float avg;
    
    printf("Enter a, b, c: ");
    scanf("%d %d %d", &a, &b, &c);
    
    sum = a + b + c;
    avg = sum / 3.0;
    
    printf("Average = %.2f\n", avg);
    return 0;
}

ตัวอย่างที่ 2: เส้นรอบวงวงกลม


#include 
#define PI 3.14159

int main() {
    float r, c;
    printf("Enter radius: ");
    scanf("%f", &r);
    c = 2 * PI * r;
    printf("Circumference = %.4f\n", c);
    return 0;
}