c++中编译单元是如何定义的?
可能的重复:
什么是 C++ 中的“翻译单元”
人们常说C/C++ 中声明的静态变量在编译单元中不可见?这是否意味着每个 .c 或 .cpp 文件都是一个单独的编译单元? .h 文件和 .h 文件中声明的静态变量怎么样? .h 文件是否也被视为单独的编译单元?
Possible Duplicate:
What is a “translation unit” in C++
It is often said that the static variables declared in C/C++ are not visible across compilation units ? Does this mean that each .c or .cpp file is a separate compilation unit ? What about a .h file and the static variables declared in the .h file ? Is .h file also considered as a separate compilation unit ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
头文件没有单独的生命,只是它们的内容被
#included
到 .c 或 .cpp 文件中。但由于#include 由预处理器处理,编译器不知道不同的头文件;它只将生成的代码列表视为输入。这就是所谓的编译单元:一个源文件,其所有#include
指令被相关头文件和所有其他处理的预处理器语句的内容替换(例如<代码>#define、#ifdef
等)。Header files have no separate life, only their content is
#included
into .c or .cpp files. But since#include
is handled by the preprocessor, the compiler has no knowledge about distinct header files; it only sees the resulting code listing as input. This is what is called a compilation unit: a source file with all its#include
directives replaced by the content of the relevant header files and all other preprocessor statements processed (like#define
,#ifdef
etc.).C 和 C++ 编译(通常)分为三个独立的步骤:
只要有#include 或宏,预处理器就会用实际值扩展该表达式。对于
#include
,整行都将替换为 .h 文件内容。实际的编译器(通常)不知道任何头文件,它将编译单元视为大的 .c 或 .cpp 文件。
“通常”部分来自这样的事实:某些编译器通过将预编译头存储在某种缓存中来优化头包含,但效果是相同的。
C and C++ compilation is (usually) divided in three independent steps:
Wherever there is an
#include
or a macro, the preprocessor expands that expression with the actual value. In the case of an#include
that entire line is replaced with the .h file contents.The actual compiler is (usually) not aware of any header file, it sees a compilation unit as a big .c or .cpp file.
The "usually" part comes from the fact that some compilers optimizes header inclusion by storing a precompiled header in some sort of cache, but the effect is the same.
编译器仅处理源文件,通常扩展名为 .c 或 .cpp。编译器并不真正关心包含的文件:就编译器通常实现而言,每个 .c/.cpp 文件都会重新处理,无论读取什么 .h 文件(由预处理器提供)。
这就是我们谈论“编译单元”的原因:一次性编译的东西,其结果随后可以链接在一起形成可执行文件。
The compiler only processes source files, usually with the extension .c or .cpp. The compiler doesn't really care about the files that are included: as far as the compiler is usually implemented, each .c/.cpp file is processed anew, whatever .h files are read (courtesy of the preprocessor).
This is why we talk about 'compilation units': something that is compiled in one go, the results of which may subsequently be linked together into executables.