23

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 ?

phuclv
  • 37,963
  • 15
  • 156
  • 475
cppdev
  • 6,833
  • 13
  • 40
  • 45
  • Possible duplicate: http://stackoverflow.com/questions/1106149/what-is-a-translation-unit-in-c – Flexo Feb 14 '11 at 12:44
  • 9
    Technically a duplicate, but that presumes that you know that a "compilation unit" is the same as a "translation unit". – MSalters Feb 14 '11 at 12:55

3 Answers3

42

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.).

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
Péter Török
  • 114,404
  • 31
  • 268
  • 329
12

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.

Yogu
  • 9,165
  • 5
  • 37
  • 58
vz0
  • 32,345
  • 7
  • 44
  • 77
5

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.

Pontus Gagge
  • 17,166
  • 1
  • 38
  • 51