Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 626
cppdev Avatar asked Feb 14 '11 12:02

cppdev


People also ask

What is a compilation unit in C?

A compilation unit refers to a C source code which is compiled and treated as a single logical unit. It is generally one or more complete files; however, it also may be a certain part of a file if the #ifdef preprocessor directive is applied to choose specific code sections.

Which of the following can be described as compilation unit?

A compilation unit is C source code that is compiled and treated as one logical unit. The compilation unit is usually one or more entire files, but can also be a selected portion of a file if, for example, the #ifdef preprocessor directive is used to select specific code sections.

Is a header file a compilation unit?

h file ? Is . h file also considered as a separate compilation unit ? Technically a duplicate, but that presumes that you know that a "compilation unit" is the same as a "translation unit".

Is object file compilation unit?

Object file, in typical cases, is the result of the compilation unit being compiled. Executable file is the result of linking the object file(s) of a project, together with the runtime library function.


2 Answers

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.

like image 161
Péter Török Avatar answered Sep 22 '22 19:09

Péter Török


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.

like image 27
vz0 Avatar answered Sep 22 '22 19:09

vz0