Single Compilation Unit

From Wikipedia, the free encyclopedia
Jump to: navigation, search

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


Usually a C/C++ development environment assumes that .c/.cpp source files are preprocessed into translation units which are then translated (compiled) separately by the compiler into multiple object (.o or .obj) files. These object files can then be linked together to create a single executable file or library. However, this leads to multiple passes being performed on common header files, and with C++, multiple template instantiations of the same templates in different translation units.

The Single Compilation Unit technique uses pre-processor directives to "glue" different translation units together at compile-time rather than at link-time. This reduces the overall build time, but increases the build time required after making minor changes to any source file that is included in the Single Compilation Unit. Therefore, this technique is appropriate for modules which consist of infrequently modified source files.

SCU also allows an optimizer to trace deeper relations between functions, therefore allowing optimizations such as inlining, and helps avoiding implicit code bloat due to exceptions, side effects, and register allocation, which are generally overlooked by the classic scheme of using separate modules, and not always achieved by the use of precompiled headers [clarification needed].


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

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

Suppose foo.cpp and bar.cpp are:

#include <iostream> // A large, standard header
#include "bar.h"    // Declaration of function 'bar'
int main()          // Definition of function 'main'
#include <iostream> // The same large, standard header
void bar()          // Definition of function 'bar'

Now the standard header file (iostream) is compiled only once, and function bar may be inlined into function main, despite being from another module.

See also[edit]