Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantages of condensing .cpp files?

When compiling a 'static library' project in MSVC++, I often get .lib files that are several MB in size. If I use conditional macros and include directives to "condense" all my .cpp files in one .cpp file at compile time, the .lib file size decreases considerably.

Are there any disadvantages with this practice?

like image 808
Baltram Avatar asked Dec 17 '22 04:12

Baltram


2 Answers

The main problem of Unity Builds as they are called is that they break the way C++ works.

In C++, a source file, with its includes preprocessed, is called a Translation Unit. Some symbols are "private" to this translation unit:

  • symbols declared static at namespace level
  • anything declared in anonymous namespace

If you merge several C++ files, then the compiler will share those private symbols among all the files that are merged together since from its point of view this has become a single Translation Unit.

You will get an error if two local classes suddenly have the same name, and idem for constants. Annoying as hell, but at least you are notified.

For functions however, it may break silently because of overload. When before the compiler would pick static void launch(short u); for your call to launch(1), then suddenly it will shift to static void launch(int i, Target t = "Irak");. Oups ?

Unity Builds are dangerous. What you are looking for is called WPO (Whole Program Optimization) or LTO (Link Time Optimization), look into the innards of your compiler manual to know how to activate it.

like image 168
Matthieu M. Avatar answered Jan 11 '23 06:01

Matthieu M.


A disadvantage would be if you change a single line in the cpp you have to compile the whole code.

like image 37
Martin Brandl Avatar answered Jan 11 '23 05:01

Martin Brandl