Hands-On High Performance Programming with Qt 5
上QQ阅读APP看书,第一时间看更新

Workaround – unity builds

A unity build (also known as a Single Compilation Unit or jumbo) is actually a means to speed up the compilation of C++ projects, because it cuts down on times needed for the processing of single files. A unity build looks as simple as the following:

// UnityBuildFile.cpp
#include "Widgets.cpp"
#include "Gui.cpp"
#include "Main.cpp"

As we can see, one has only to include all the implementation files in a single main build file. The time savings, reported to be as high as 90%, come from parsing the common includes only once, less instantiation of templates, less invocations of compiler, and less work for the linker.

But apart from that, we get our WPO free of charge as everything is in one place and totally visible to the compiler!

There are some caveats though, starting with its tremendous memory usage and ending with miscompilations as some overloads can be suddenly better than in a non-unity build or some macros are applied out of their scopes. An incremental build is also out of the question. Despite those problems, this technique is used in the industry, for example, for WebKit and the Unreal game engine. There are plugins for CMake supporting unity builds, and Visual Studio 2017 even contains experimental native support for that.