预处理程序如何在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 << "PI的值:" << PI << endl;
   return 0;
}

输出结果

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