C/C++ 中預處理器是如何工作的?


在這裡,我們將瞭解預處理器在 C 或 C++ 中是如何工作的。讓我們看看什麼是預處理器。

預處理器是指令,它們指示編譯器在實際編譯開始之前預處理資訊。

所有預處理器指令都以 # 開頭,並且在一行中預處理器指令之前只能出現空格字元。預處理器指令不是 C++ 語句,因此它們不會以分號 (;) 結尾。

您已經在所有示例中都看到了 #include 指令。此宏用於將標頭檔案包含到原始檔中。

C++ 支援許多預處理器指令,例如 #include、#define、#if、#else、#line 等。讓我們看看重要的指令 -

#define 預處理器

#define 預處理器指令建立符號常量。符號常量稱為宏,指令的一般形式為 -

#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

條件編譯

有一些指令可用於編譯程式原始碼的選定部分。此過程稱為條件編譯。

條件預處理器結構非常類似於“if”選擇結構。考慮以下預處理器程式碼 -

#ifndef NULL
#define NULL 0
#endif

您可以為除錯目的編譯程式。您還可以使用單個宏開啟或關閉除錯,如下所示 -

#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endif

如果在 #ifdef DEBUG 指令之前已定義了符號常量 DEBUG,則這會導致 cerr 語句在程式中進行編譯。您可以使用 #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

更新於: 2019年7月30日

318 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.