简体   繁体   English

在C ++上进行预处理器解析

[英]Pre-processor parsing on C++

If we want to use user input to do something in a program, or print a result we need to 如果要使用用户输入在程序中执行某项操作或打印结果,则需要

 #include <iostream>

otherwise, cout and cin will not be acknowledged by the compiler.However the command #include is a pre-processor command. 否则,编译器将不会确认coutcin但是命令#include是预处理程序命令。 And when I was writing my program the following happened. 当我编写程序时,发生了以下情况。 I wrote the following code : 我写了以下代码:

#define PRINT_DEBUG_INFO(a) {cout << “Info: ” << a << endl;}
#include <iostream>

And no errors popped up.How is it possible to use cout before including iostream ? 而且没有弹出错误。在包含iostream之前如何使用cout Even if I declare the PRINT_DEBUG_INFO(a) without including iostream , I don't get a compiling error. 即使我声明PRINT_DEBUG_INFO(a)而不包含iostream ,也不会出现编译错误。
Can somebody explain me why this happens? 有人可以解释一下为什么会这样吗?

The preprocessor doesn't require any C++ declared symbols to be evaluated to do its work. 预处理程序不需要评估任何C ++声明的符号即可完成其工作。

It's pure text processing , so defining a macro like 这是纯文本处理 ,因此定义一个宏

#define PRINT_DEBUG_INFO(a) {cout << “Info: ” << a << endl;}

and expanding it like 并扩大它像

#include <iostream>

void foo {
  int a = 5;
  PRINT_DEBUG_INFO(a);
}

will become 会变成

// All the literal stuff appearing in <iostream>

void foo {
  int a = 5;
  {cout << “Info: ” << a << endl;};
}

So there's nothing checked regarding proper C++ syntax during definition or expansion of the macro. 因此,在宏的定义或扩展过程中,没有检查有关正确的C ++语法的内容。

These statements will be processed further by the C++ compiler, which will complain about cout isn't declared in the global scope. 这些语句将由C ++编译器进一步处理,它将抱怨cout没有在全局范围内声明。

To fix this, declare your macro like 要解决此问题,请声明您的宏,例如

#define PRINT_DEBUG_INFO(a) {std::cout << “Info: ” << a << std::endl;}

您定义了PRINT_DEBUG_INFO,但未使用它,因此编译器没有任何编译或抱怨的地方。

You are just defining PRINT_DEBUG_INFO(a) and not using it. 您只是在定义PRINT_DEBUG_INFO(a)而未使用它。 When you actually use it inside your program you will get the error that cout is not defined. 当您在程序中实际使用它时,会出现未定义cout的错误。

When you are not actually using it, the compiler finds no place to substitute the defined constant. 当您实际上不使用它时,编译器找不到替换定义的常量的位置。 When you actually use it, the program gets expanded during compilation and shows you the error. 当您实际使用它时,程序将在编译过程中扩展并显示错误。

And moreover there is a bracket in your macro which gets expanded with brackets and may lead to error. 此外,您的宏中还有一个括号,该括号会用括号扩展,并可能导致错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM