开发者

How is compilation unit defined in c++? [duplicate]

This question already has answers here: 开发者_开发知识库 Closed 11 years ago.

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 seperate 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 ?


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.


C and C++ compilation is (usually) divided in three independent steps:

  • Preprocessing, involving macro and #include expansions.
  • Compiling, converting source code to binary code and generating intermediante object files.
  • Linking, joining the object files in a single ELF or EXE file.

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜