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

Macros และ Preprocessors ใน C

C Preprocessor ไม่ใช่ส่วนของคอมไพเลอร์ แต่เป็นขั้นตอนแยกต่างหากในกระบวนการคอมไพล์ อย่างง่าย C Preprocessor เป็นเครื่องมือแทนที่ข้อความ (text substitution) สั่งให้คอมไพเลอร์ทำ pre-processing ก่อนคอมไพล์จริง เรียกว่า CPP

คำสั่ง preprocessor ทั้งหมดขึ้นต้นด้วย # ต้องเป็นตัวอักษรแรกที่ไม่ใช่ blank และเพื่อความอ่านง่าย ควรเริ่มที่คอลัมน์แรก คำสั่งสำคัญ:

Sr.No Directives & Descriptions
1#define
แทนที่ preprocessor macro
2#include
แทรก header จากไฟล์อื่น
3#undef
ยกเลิก preprocessor macro
4#ifdef
คืนค่า true ถ้า macro ถูกกำหนด
5#ifndef
คืนค่า true ถ้า macro ไม่ได้ถูกกำหนด
6#if
ทดสอบเงื่อนไข compile-time
7#else
ทางเลือกสำหรับ #if
8#elif
#else และ #if ในคำสั่งเดียว
9#endif
จบ preprocessor conditional
10#error
พิมพ์ข้อความผิดพลาดบน stderr
11#pragma
ส่งคำสั่งพิเศษให้คอมไพเลอร์

ตัวอย่าง Preprocessors:

#define MAX_ARRAY_LENGTH 20

บอก CPP แทนที่ MAX_ARRAY_LENGTH ด้วย 20 ใช้ #define สำหรับค่าคงที่เพื่อความอ่านง่าย

#include <stdio.h>
#include "myheader.h"

บอก CPP ดึง stdio.h จาก System Libraries และเพิ่มข้อความในไฟล์ปัจจุบัน บรรทัดถัดไปดึง myheader.h จาก local directory

#undef FILE_SIZE
#define FILE_SIZE 42

บอก CPP ยกเลิก FILE_SIZE เดิม และกำหนดเป็น 42

#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif

บอก CPP กำหนด MESSAGE ก็ต่อเมื่อ MESSAGE ยังไม่ถูกกำหนด

#ifdef DEBUG
/* Your debugging statements here */
#endif

บอก CPP ประมวลผลคำสั่งที่ล้อมรอบ ก็ต่อเมื่อ DEBUG ถูกกำหนด ใช้งานได้ถ้าส่ง flag -DDEBUG ให้ gcc ตอนคอมไพล์ สลับ debugging on/off ระหว่างคอมไพล์ได้

Predefined Macros

ANSI C กำหนด macro หลายตัว แม้ใช้ได้ในโปรแกรม predefined macros ไม่ควรแก้ไขโดยตรง

Sr.No Macro & Descriptions
1__DATE__
วันที่ปัจจุบันเป็น character literal รูปแบบ "MMM DD YYYY"
2__TIME__
เวลาปัจจุบันเป็น character literal รูปแบบ "HH:MM:SS"
3__FILE__
ชื่อไฟล์ปัจจุบันเป็น string literal
4__LINE__
หมายเลขบรรทัดปัจจุบันเป็น decimal constant
5__STDC__
เป็น 1 เมื่อคอมไพเลอร์เป็นไปตามมาตรฐาน ANSI

ตัวอย่าง

#include <stdio.h>
int main() {
  printf("File :%s\n", __FILE__ );
  printf("Date :%s\n", __DATE__ );
  printf("Time :%s\n", __TIME__ );
  printf("Line :%d\n", __LINE__ );
  printf("ANSI :%d\n", __STDC__ );
}

ผลลัพธ์

File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1