Preprocessors คือคำสั่งที่ให้คำสั่งกับคอมไพเลอร์เพื่อประมวลผลข้อมูลก่อนที่การคอมไพล์จริงจะเริ่มต้น
คำสั่ง Preprocessor ทั้งหมดขึ้นต้นด้วย # และอักขระ whitespace เท่านั้นที่อาจปรากฏก่อนคำสั่ง preprocessor บนบรรทัดหนึ่ง คำสั่ง Preprocessor ไม่ใช่คำสั่ง C++ จึงไม่จบด้วยเครื่องหมาย semicolon (;)
คุณเคยเห็นคำสั่ง #include ในทุกตัวอย่างแล้ว มักโครนี้ใช้เพื่อรวมไฟล์ header เข้าไปในไฟล์ต้นทาง
มีคำสั่ง preprocessor หลายตัวที่ C++ รองรับ เช่น #include, #define, #if, #else, #line เป็นต้น มาดูคำสั่งสำคัญๆ -
Preprocessor #define
คำสั่ง #define สร้าง symbolic constants (ค่าคงที่เชิงสัญลักษณ์) ค่าคงที่เชิงสัญลักษณ์นี้เรียกว่า macro และรูปแบบทั่วไปคือ -
#define macro-name replacement-text
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
#define PI 3.14159
int main() {
cout << "Value of PI :" << PI << endl;
return 0;
}
ผลลัพธ์
Value of PI :3.14159
Conditional Compilations (การคอมไพล์เงื่อนไข)
มีคำสั่งหลายตัวที่ใช้คอมไพล์ส่วนเฉพาะของซอร์สโค้ด กระบวนการนี้เรียกว่า conditional compilation
โครงสร้าง preprocessor แบบเงื่อนไขคล้ายกับโครงสร้างการเลือก 'if' พิจารณาโค้ด preprocessor ต่อไปนี้ -
#ifndef NULL
#define NULL 0
#endif
คุณสามารถคอมไพล์โปรแกรมเพื่อการดีบักได้ คุณยังสามารถเปิด/ปิดการดีบักโดยใช้ macro เดียวได้ดังนี้ -
#ifdef DEBUG
cerr << "Variable x = " << x << endl;
#endif
สิ่งนี้ทำให้คำสั่ง cerr ถูกคอมไพล์เข้าโปรแกรม หากค่าคงที่เชิงสัญลักษณ์ DEBUG ถูกกำหนดก่อนคำสั่ง #ifdef DEBUG คุณสามารถใช้ #if 0 เพื่อคอมเมนต์ส่วนของโปรแกรมได้ดังนี้ -
#if 0
code prevented from compiling
#endif
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
#define DEBUG
#define MIN(a,b) (((a)<(b)) ? a : b)
int main() {
int i, j;
i = 100;
j = 30;
#ifdef DEBUG
cerr << "Trace: Inside main function" << endl;
#endif
#if 0
/* This is commented part */
cout << MKSTR(HELLO C++) << endl;
#endif
cout << "The minimum is " << MIN(i, j) << endl;
#ifdef DEBUG
cerr << "Trace: Coming out of main function" << endl;
#endif
return 0;
}
ผลลัพธ์
Trace: Inside main function The minimum is 30 Trace: Coming out of main function