Disadvantages of condensing .cpp files?

When compiling a “static library” project in MSVC ++, I often get .lib files of several MB in size. If I use conditional macros and include directives to “compress” all my .cpp files into a single .cpp file at compile time, the size of the .lib file is greatly reduced.

Are there any flaws in this practice?

+4
source share
4 answers

The main problem with Unity Builds, as they are called, is that they disrupt C ++.

In C ++, the source file, including the pre-processed one, is called the translation unit. Some private characters for this translation unit:

  • declared namespace-level static characters
  • everything declared in an anonymous namespace

If you combine several files in C ++, the compiler will share these personal characters between all files that are combined together, since from his point of view it has become a single translation module.

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

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

Unity builds are dangerous. What you are looking for is called WPO (Optimization of the entire program) or LTO (Optimization of communication time), check out the internal documents of your compiler to find out how to activate it.

+6
source

The downside would be that if you change one line in cpp, you have to compile all the code.

+4
source

Your file may become more complex and you will have to recompile it, even if you just change one file with one source code. In addition, there is no real flaw, unless files override local functions or variables that can damage you when merging is all (for example, due to several definitions within the same translation unit).

The size reduction that you notice is related to the improved optimization that becomes available this way (for example, reusing more code). Depending on your code, you can get similar results by including all optimizations for size, as well as optimizing link times, which may lead to some acceptable solution between both approaches.

+1
source

As a rule, confusing practice includes cpp in another cpp (at least you should leave an explanatory comment about why you did this).

+1
source

Source: https://habr.com/ru/post/1393506/


All Articles