C/C++ 预处理器

本文最后更新于:5 个月前

宏定义

#define <宏> <字符串>

一个标识符被宏定义后,该标识符便是一个宏名。

标识符是用来标识变量、函数、类、模块,或任何其他用户自定义项目的名称,用它来命名程序正文中的一些实体,比如函数名、变量名、类名、对象名等。

这时,在程序中出现的是宏名。编译器在开始编译之前,先将程序中的宏替换成相应的字符串,再执行编译。

#undef

这是一个和 #define 配套的指令。使用该指令可以告知编译器在后续代码中移除当前宏的定义。

#if和她的朋友们

#if 表达式

这里的语法和if很类似,如果表达式非零 #if 1 ,则编译下方的语句,反之 #if 0 则忽略不编译。

1
2
3
4
5
6
7
8
9
#include <iostream>
int main(){
#if 1
std::cout << "True";
#elif 0
std::cout << "False";
#endif
return 0;
}

#endif

细心的读者应该已经注意到了,在上一个实例的结尾我们使用了#endif。这个指令用于告诉编译器,关闭与之临近的#if指令。

#else & #elif 表达式

这两个命令类似于c/c++中的elseelse if

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
int main(){
#if _WIN32
std::cout << "This is Windows.";
#elif __linux__
std::cout << "This is Linux.";
#else
std::cout << "Unknow operating system.";
#endif
return 0;
}

#ifdef & #ifndef

这两个命令可以有以下等效
#ifdef identifier => #if defined identifier
#ifndef identifier => #if !defined identifier
如果identifier被定义了,则 #ifdef identifier 等效于 #if 1 。如果没有被定义则等效于 #if 0

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#define PI 3.14159

int main(){
#ifdef PI
std::cout << PI;
#else
std::cout << "PI is not defined.";
#endif
return 0;
}

输出:

1
3.14159

#error <自定义错误信息>

我们这里来举一个一个例子

1
2
3
4
5
6
7
8
9
//PI没有被定义
#include <iostream>
int main(){
#ifndef PI
#error PI is not defined.
#endif
std::cout << "hello,world!";
return 0;
}

输出:

1
#error PI is not defined.

这里可以看到,编译器输出了我们预先定义的错误信息,并且并没有完成编译(hello,world!并没有被输出)。

#line

1
2
3
4
5
6
7
8
9
10
11
12
13
//test.cpp
#include <stdio.h>

int main()
{
printf( "This code is on line %d, in file %s\n", __LINE__, __FILE__ );
#line 10
printf( "This code is on line %d, in file %s\n", __LINE__, __FILE__ );
#line 20 "hello.cpp"
printf( "This code is on line %d, in file %s\n", __LINE__, __FILE__ );
printf( "This code is on line %d, in file %s\n", __LINE__, __FILE__ );
return 0;
}

输出:

1
2
3
4
This code is on line 6, in file test.cpp
This code is on line 10, in file test.cpp
This code is on line 20, in file hello.cpp
This code is on line 21, in file hello.cpp

C/C++ 预处理器
https://blog.794td.cn/C-preprocessor.html
作者
794TD
发布于
2022年10月7日
许可协议