C++预定义指令

  • 2022 年 11 月 12 日
  • 笔记

C++预定义指令

1.预定义器

以#开头的命令,称之为预定义器指令。预定义器指令不在编译器中执行,而是在预定义器中运行。

常见的预定义器指令为

//文件包含指令
#include 
//宏定义指令
#define
#undef
//条件编译指令
#ifdef
#endif
#ifndef
#endif
#if
#else

2.预定义表示宏

__cplusplus:当翻译单元编译为 C++ 时,定义为整数文本值。 其他情况下则不定义。
__ DATE __:当前源文件的编译日期。
__ FILE __:当前源文件的名称。
__ LINE __:定义为当前源文件中的整数行号。
__ func __ 作为函数本地静态 const 数组的封闭函数的未限定和未限定名称 char。
void example()
{
    printf("%s\n", __func__);
}
cout << "This is the line number " << __LINE__;
cout << " of file " << __FILE__ << ".\n";
cout << "Its compilation began " << __DATE__;
cout << " at " << __TIME__ << ".\n";
cout << "The compiler gives a __cplusplus value of " << __cplusplus;
example();

3.宏定义使用

宏定义语法:

#define identifier replacement // 宏定义
#undef identifier // 取消宏定义

详细使用:

#define Math 10//值形态
#define PI 100
#define GetSum(a,b) (a)+(b)//函数宏,函数宏中的变量最好用()包裹,以免发生报错

4.条件编译

#ifdef PI//条件编译,只有在PI宏已经定义后才可以进行编译
    std::cout << PI << std::endl;
#endif
#ifndef PT
  std::cout<<"在PT宏没有被定义的时候打印该行数据"<<endl;
#endif
 //#if #else ,和if,else语句类似

5.报错预定义符

#error
//该预定义符,一般用于编译调试的时候,编译器在执行到这里的时候,自动报错,中断程序

6.line处理

#line 10 "文件名"
//将下面的代码,行数和文件名设置为line设置的行数和文件名
//如果不设定的话,行数和文件名自动设置为改行所在的行数和文件名

7.代码案列

//预处理指令和宏
#include <iostream>
#include<stdio.h>
//宏定义
#define Math 10//值形态
#define PI 100
//取消宏定义,取消宏定义放到main()之前,则会报错.需要放在mian函数之中
//#undef Math
#define GetSum(a,b) (a)+(b)//函数宏
using namespace std;

void example()
{
    printf("%s\n", __func__);
}


int main(int argc, char *argv[])
{
    #undef Math//取消宏定义
    int a=10;
    int b=10;
    int c=GetSum(a,b);//调用函数宏
    cout<<"c="<<c<<endl;

#ifdef PI//条件编译,只有在PI宏已经定义后才可以进行编译
    std::cout << PI << std::endl;
#endif
#ifndef PT
  std::cout<<"在PT宏没有被定义的时候打印该行数据"<<endl;
#endif

 //#if #else ,和if,else语句类似

 //预定义宏
  /*
   预定义宏仅针对特定生成环境或编译器选项定义。 除非另行说明,否则这些宏的定义范围适用于整个翻译单元。
   定义后,预处理器先将这些宏展开为指定的值,然后再编译。 预定义宏不带参数,不能重新定义。
  */
    cout << "This is the line number " << __LINE__;
    cout << " of file " << __FILE__ << ".\n";
    cout << "Its compilation began " << __DATE__;
    cout << " at " << __TIME__ << ".\n";
    cout << "The compiler gives a __cplusplus value of " << __cplusplus<<endl;


    //#line处理
    cout<<"该行代码所在的行数为"<<__LINE__<<"文件所在的位置为"<<__FILE__<<endl;
#line 50 "main.cpp" //#line指令允许我们控制这两件事,代码文件中的行号以及发生错误时我们希望显示的文件名。它的格式是
    cout<<"该行代码所在的行数为"<<__LINE__<<"文件所在的位置为"<<__FILE__<<endl;

//#error用于报错,在调试程序的时候用得上

//预定义表示符
     example();
/*
__cplusplus:当翻译单元编译为 C++ 时,定义为整数文本值。 其他情况下则不定义。
__ DATE __:当前源文件的编译日期。
__ FILE __:当前源文件的名称。
__ LINE __:定义为当前源文件中的整数行号。
*/
    cout << "This is the line number " << __LINE__;
    cout << " of file " << __FILE__ << ".\n";
    cout << "Its compilation began " << __DATE__;
    cout << " at " << __TIME__ << ".\n";
    cout << "The compiler gives a __cplusplus value of " << __cplusplus;
   return 0;
}