Why does C++ compilation take so long?
During the process of conversion of the source code which is in a high-level language to the machine code(binary), two major things happen, compiling and linking. Let’s confine our discussion about compiling for now.
The compiler’s primary task is to produce object code from our source code files. The first step it does is that it makes sure all the preprocessor statements i.e., the #include, #define, #if etc. get evaluated. The next steps include loading and compiling the header files, parsing(resolving), managing templates, code optimization, etc. All these steps mentioned above are in some way responsible for the slower compilation of a C++ program.
The step involving the inclusion, loading and compiling of the header files tops amongst the reasons mentioned above for slow compilation. For instance, if we consider our very massive header file <iostream.h>, we’ll be astonished to find 50,623 lines in the preprocessor file (object file). This means that the header file will try to include all this 50,623-line long information into our program.
Next comes parsing. It uses syntax highlighting for the language elements identification, including the following elements:
- Continuation character
- Comments etc
The inclusion of these majorly depends on the context and is very difficult in rephrasing and this takes a lot of time.
Optimization is a phase where the compiler tries to improve the intermediate code by making it use fewer resources, for example, CPU, memory, to get a faster-running machine code. In this process, it must make sure that:
- In any way, it doesn’t change the meaning of the program.
- It improves the performance and speed of the program.
- It maintains reasonable compilation time.
- It doesn’t delay the overall compiling process.
In addition to these, the main reason is to open and close files i.e., The compiler has to open the .h file, read each line in it and close it. This is again a tedious process.