[英]Preprocessor directives in C++
I have read several articles about how Preprocessor directives work in C++. It's clear to me that Preprocessor directives are managed by the pre-processor before compilation phase.我在 C++ 中阅读了几篇关于预处理器指令如何工作的文章。我很清楚预处理器指令在编译阶段之前由预处理器管理。 Let's consider this code:让我们考虑一下这段代码:
#include <iostream>
#ifndef N
#define N 10
#endif
int main(){
int v[N];
return 0;
}
The Pre-processor will elaborate the source code by performing text replacement, so this code during compilation phase would be equivalent to:预处理器将通过执行文本替换来详细说明源代码,因此编译阶段的这段代码相当于:
int main(){
int v[10];
return 0;
}
Now my question is: Can I define a Macro by setting its value equal to a function?现在我的问题是:我可以通过将其值设置为等于 function 来定义宏吗? It looks a bit weird to me but the answer is yes.这对我来说看起来有点奇怪,但答案是肯定的。
#include<iostream>
#include <limits>
#ifndef INT_MIN
#define INT_MIN std::numeric_limits<int>::min()
#endif
int get_max(){
return 5;
}
#ifndef INT_MAX
#define INT_MAX get_max()
#endif
int main()
{
std::cout << INT_MIN << " " << INT_MAX;
return 0;
}
Conceptually I'm not understanding why this code works, the pre-processor have to replace text before compilation phase, so how could a function be invoked (In this case get_max() function)?从概念上讲,我不明白为什么这段代码有效,预处理器必须在编译阶段之前替换文本,那么如何调用 function(在本例中为 get_max()函数)?
Functions invoking is a task managed by compiler?函数调用是由编译器管理的任务? isn't it?不是吗?
How could Pre-processor get access to std::numeric_limits::min() ?预处理器如何访问std::numeric_limits::min() ? This value is present inside the "limits" library, but if I understand correctly the libraries's inclusion is done by compiler.这个值存在于“限制”库中,但如果我理解正确的话,库的包含是由编译器完成的。
For the sake of illustration I removed the includes from your code:为了说明起见,我从您的代码中删除了包含:
#ifndef INT_MIN
#define INT_MIN 0
#endif
int get_max(){
return 5;
}
#ifndef INT_MAX
#define INT_MAX get_max()
#endif
int main()
{
return INT_MIN + INT_MAX;
}
Then I invoked gcc with -E
to see the output after preprocessing:然后我用-E
调用 gcc 来查看预处理后的 output:
int get_max(){
return 5;
}
int main()
{
return 0 + get_max();
}
This is the code that will get compiled.这是将要编译的代码。 The preprocessor does not call the funciton.预处理器不调用函数。 It merely replaces INT_MAX
with get_max()
.它只是将INT_MAX
替换为get_max()
。
Can I define a Macro by setting its value equal to a function?我可以通过将其值设置为等于 function 来定义宏吗?
Thats not what you do.那不是你做的。 #define INT_MAX get_max()
just tells the preprocessor to replace INT_MAX
with get_max()
. #define INT_MAX get_max()
只是告诉预处理器用get_max()
替换INT_MAX
。 The preprocessor doen't know nor care if get_max()
is a function call or something else.预处理器不知道也不关心get_max()
是 function 调用还是其他。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.