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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP