预处理在编译器中到底意味着什么 [英] What does preprocessing exactly mean in compiler
问题描述
我试图理解typedef和define之间的区别.在关于SO的先前问题中,有很多不错的帖子a>,但是我听不懂
I am trying to understand the difference between a typedef and define. There are a lot of good posts specially at this previous question on SO, however I can't understand the post that states
#define
是预处理器令牌:编译器本身将永远看不到它.typedef
是一个编译器令牌:预处理器并不关心它.
#define
is a preprocessor token: the compiler itself will never see it.
typedef
is a compiler token: the preprocessor does not care about it.
任何人都可以再详细解释一下.我对这里的预处理器一词感到困惑.
Could anyone please explain this with a little more detail. I am confused with the term preprocessor here.
推荐答案
预处理器是在之前运行的程序,本质上执行文本替换.当您写时:
The pre-processor is a program that runs before the compiler and essentially performs text substitution. When you write:
#define X 10
int main()
{
int x = X;
}
预处理器将该文件作为输入,执行该操作并输出:
The pre-processor take that file as input, does it's thing, and outputs:
int main()
{
int x = 10;
}
然后,编译器使用预处理后的输出执行操作.
And then the compiler does its thing with the pre-processed output.
typedef
是编译器可以理解的结构.当您写时:
typedef
on the other hand is a construct that the compiler understands. When you write:
typedef unsigned int uint_32;
编译器知道 uint32
实际上是 unsigned int
的别名.该别名由编译器本身处理,比简单的文本替换包含更多的逻辑.举一个简单的例子,这很明显:
The compiler knows that uint32
is actually an alias for unsigned int
. This alias is handled by the compiler itself and involves a bit more logic than simple text substitution. This becomes obvious with a simple example:
typedef int my_int;
int main()
{
unsigned my_int x; // oops, error
}
如果 typedef
是一种简单的文本替换机制(如预处理器一样),则该方法会起作用,但不允许这样做,并且将无法编译.
If a typedef
were a simple text substitution mechanism (like the pre-processor is) then that would work, but it is not allowed and will fail to compile.
这篇关于预处理在编译器中到底意味着什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!