22

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 ?

Community
  • 1
  • 1
cppdev
  • 6,683
  • 12
  • 38
  • 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

38

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.

Péter Török
  • 112,083
  • 30
  • 265
  • 327
11

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
  • 8,629
  • 4
  • 33
  • 53
vz0
  • 31,429
  • 7
  • 39
  • 75
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
  • 16,973
  • 1
  • 37
  • 50