C preprocessor ให้ลึกขึ้น



preprocessor เป็นขั้นแรกของการคอมไพล์ (บทที่ 2) — มันทำงานกับ token (คำ/สัญลักษณ์) ไม่ใช่ตัวอักษรทีละตัว ไม่รู้จัก C ไม่รู้จัก type และ ไม่แตะข้อความในสตริงหรือคอมเมนต์ (เช่น #define N 5 ไม่เปลี่ยน "N" หรือ printf("N"))

#define — ค่าคงที่

#define PI 3.14159265
#define MAX_USERS 100
#define GREETING "สวัสดี"

double area = PI * r * r;
char buf[MAX_USERS];

ก่อนคอมไพล์ preprocessor แทนที่ทุก token PI ด้วย 3.14159265 (แต่ไม่แตะ "PI" ในสตริง หรือ PIE ที่เป็นคนละ token)

const ดีกว่า #define สำหรับค่าคงที่ทั่วไป — const มีชนิด, debugger เห็นชื่อ, มี scope:

const double PI = 3.14159265;      // ดีกว่า

ใช้ #define เมื่อต้องการค่าตอน compile time จริง ๆ (ขนาดอาร์เรย์, #if) หรือ conditional compilation

มาโครมี argument — ระวัง!

#define SQUARE(x) x * x

int a = SQUARE(5);         // 5 * 5 = 25 — OK
int b = SQUARE(2 + 3);     // 2 + 3 * 2 + 3 = 11 — ไม่ใช่ 25!

preprocessor แทน x ด้วยข้อความ 2 + 3 ตรง ๆ ได้ 2 + 3 * 2 + 3 แก้: ครอบวงเล็บทุก argument และทั้งนิพจน์:

#define SQUARE(x) ((x) * (x))

int b = SQUARE(2 + 3);     // ((2 + 3) * (2 + 3)) = 25 — ถูก
int c = 100 / SQUARE(2);   // 100 / ((2) * (2)) = 25 — ถ้าไม่มีวงเล็บนอกจะเป็น 100/2*2 = 100

กับดัก side effect

#define MAX(a, b) ((a) > (b) ? (a) : (b))

int i = 15;
int m = MAX(i++, 10);      // ((i++) > (10) ? (i++) : (10))
                           // เงื่อนไข: i++ → 15 (i เป็น 16), 15 > 10 จริง
                           // สาขา true: i++ อีกครั้ง → 16 (i เป็น 17)
                           // ผลลัพธ์: m = 16, i = 17 — ประเมิน i++ สองครั้ง!

(ถ้า i เริ่มที่ 5: 5 > 10 เท็จ ไปสาขา 10 — i++ ในสาขา true ไม่ถูกประเมิน i กลายเป็น 6, m = 10 จำนวนครั้งที่ประเมินขึ้นกับว่าเข้าสาขาไหน ยิ่งคาดเดายาก)

มาโครประเมิน argument ทุกครั้งที่มันปรากฏ — MAX(f(), g()) เรียก f/g หลายครั้ง หลีกเลี่ยงส่ง expression ที่มี side effect เข้ามาโคร หรือใช้ static inline function แทน (type-safe, ประเมินครั้งเดียว):

static inline int imax(int a, int b) { return a > b ? a : b; }

มาโครหลายบรรทัด

#define SWAP(a, b) do { \
    int tmp = (a);      \
    (a) = (b);          \
    (b) = tmp;          \
} while (0)

SWAP(x, y);             // ใช้เหมือน statement — ต่อ ; ได้ปกติ

do { ... } while (0) ทำให้มาโครเป็น statement เดียวที่ใส่ ; ได้ และทำงานถูกใน if (c) SWAP(x,y); else ...

conditional compilation

#define DEBUG 1

#if DEBUG
    printf("ค่า x = %d\n", x);
#endif

#ifdef PLATFORM_WINDOWS
    #include <windows.h>
#else
    #include <unistd.h>
#endif

#ifndef NDEBUG
    assert(ptr != NULL);
#endif
  • #if EXPR / #elif / #else / #endif — EXPR ต้องเป็นค่าคงที่จำนวนเต็ม
  • #ifdef NAME = #if defined(NAME) — เช็คว่า define ไว้ไหม (ไม่สนค่า)
  • #ifndef NAME = #if !defined(NAME)

กำหนดมาโครตอนคอมไพล์:

gcc -DDEBUG=1 -DPLATFORM_LINUX prog.c -o prog

-DNDEBUG (no debug) ปิด assert() ทั้งหมด — ใช้ตอน build release

include guard — กันไฟล์ถูก include ซ้ำ

ถ้า a.h include b.h และ main.c include ทั้งคู่ — b.h ถูกแปะสองครั้ง → นิยาม struct/typedef ซ้ำ → error

// mylib.h
#ifndef MYLIB_H            // ถ้ายังไม่เคยเห็น MYLIB_H
#define MYLIB_H            // จำไว้ว่าเห็นแล้ว

typedef struct { int x, y; } Point;
void point_print(const Point *p);

#endif  // MYLIB_H

ครั้งที่สองที่ include, MYLIB_H ถูก define แล้ว เนื้อในถูกข้าม

ทางเลือกที่สั้นกว่า (รองรับเกือบทุกคอมไพเลอร์):

// mylib.h
#pragma once

typedef struct { int x, y; } Point;

ทุกไฟล์ .h ต้องมี guard หรือ #pragma once

มาโครประโยชน์ที่มากับภาษา

printf("ไฟล์ %s บรรทัด %d\n", __FILE__, __LINE__);
printf("คอมไพล์เมื่อ %s %s\n", __DATE__, __TIME__);
printf("ฟังก์ชัน %s\n", __func__);          // จริง ๆ เป็น identifier ไม่ใช่มาโคร

#define LOG(msg) fprintf(stderr, "[%s:%d] %s\n", __FILE__, __LINE__, msg)

# แปลง argument เป็นสตริง (stringize), ## เชื่อม token:

#define STR(x) #x
#define CONCAT(a, b) a ## b

STR(hello)          // "hello"
int CONCAT(my, var) = 5;   // int myvar = 5;

#define ASSERT_MSG(cond) \
    if (!(cond)) fprintf(stderr, "ล้มเหลว: " #cond "\n")

เรื่องที่คนมักพลาด

  • มาโครไม่ครอบวงเล็บ argument — SQUARE(2+3) ผิด ครอบทุก (x) และทั้งนิพจน์ ((x)*(x))
  • #define SIZE 100; มี ; เกิน — แทนที่แล้วได้ int arr[100;] error
  • ส่ง i++ เข้ามาโคร — ประเมินหลายครั้ง ใช้ static inline function แทน
  • มาโครหลายบรรทัดไม่มี do { } while (0) — พังใน if/else ที่ไม่มีปีกกา
  • ไฟล์ .h ไม่มี include guard — นิยามซ้ำ compile error เมื่อ include ทางอ้อม 2 ครั้ง
  • ใช้ #define แทน enum/const สำหรับทุกอย่าง — เสีย type safety และ debugger info
  • มาโครชื่อชนกับ identifier — #define max ... แล้วมีฟังก์ชัน max — พังหมด ตั้งชื่อมาโคร UPPER_CASE

สรุป

  • preprocessor แทนที่ token ก่อนคอมไพล์ (ไม่แตะสตริง/คอมเมนต์) — ไม่รู้จัก type
  • #define ค่าคงที่: ใช้ const/enum แทนถ้าทำได้; มาโครมี argument ครอบวงเล็บทุกตัว ((x)*(x))
  • มาโครประเมิน argument หลายครั้ง — เลี่ยง side effect, ใช้ static inline function เมื่อ type สำคัญ
  • มาโครหลายบรรทัด: do { ... } while (0)
  • #if / #ifdef / #ifndef — conditional compilation, -DNAME=val ตอนคอมไพล์
  • ทุก .h ต้องมี include guard (#ifndef X / #define X / #endif) หรือ #pragma once

บทถัดไปว่าด้วยการแยกไฟล์ .h/.c และการคอมไพล์หลาย translation unit — extern, static ระดับไฟล์, ODR