Single Compilation Unit

From Wikipedia, the free encyclopedia

Single Compilation Unit is a C/C++ technique which reduces compilation time and aids the compiler to perform program optimization even when compiler itself is lacking support for whole program optimization or precompiled headers.

[edit] Purpose

Usually C/C++ development environment assumes that .c/.cpp files (translation units) are preprocessed and translated separately by compiler to object (.o or .obj) files, which can be then linked together to create an executable file. This leads to multiple passes on common header files and multiple template instantiations of same templates in different translation units (C++ compiler specific). Single Compilation Unit technique uses preprocessor to "glue" different translation units at compile time, not link-time, therefore reducing build time at cost of minor changes recompilation speed in one .cpp file. So SCU may be appropriate for some modules which consist of infrequently modified source files.

SCU also allows optimizer to trace deeper relations between functions, therefore allowing optimizations such as inlining and helps avoiding implicit code bloat due exceptions, side effects, register allocation which are generally overlooked in classic scheme with separated modules and not always achieved by using precompiled headers.

[edit] Usage

For example, if you have source files foo.cpp and bar.cpp, they can be placed in Single Compilation Unit as follows:

#include "foo.cpp"
#include "bar.cpp"

suppose foo.cpp and bar.cpp are -

//foo.cpp
#include <iostream> //large standard header
#include "bar.hpp" //declaration of function 'bar'

int main() 
{ 
  bar();
}
//bar.cpp
#include <iostream> //large standard header

void bar()
{
  ...
}  

now standard include file <iostream> is compiled only once, and function bar from another module may be inlined into function main.

[edit] See also