A Brief Introduction
Compiling C++ projects is a frustrating task most days. Seemingly nonexistent errors keeping your program from successfully compiling can be annoying, especially since you know you wrote it perfectly the first time, right?
Have no fear, Christian is here to explain the role of the C++ compiler for you. I'm learning more and more about C++ these days and decided to reteach this concept so that I can cement it even further in my own head. However, C++ is not the only compiled language. Check out the Wikipedia entry for compiled languages for more examples of compiled languages.
I'll start with a wonderful, graphical way to conceptualize the C++ compiler. View this page on C++ compilation to see the graphic and an explanation. Kurt MacMahon, a professor from NIU, explains the compiler in a succinct, but easy explanation. The goal of the compilation process is to take the C++ code and produce a shared library, dynamic library, or an executable file.
Let's break down the compilation process. There are four major steps to compiling C++ code. The first step is to expand
the source code file to meet all dependencies. The C++ preprocessor includes the code from all the header files, such
#include <iostream>. Now, what does that mean? The previous example includes the
iostream header. This tells the
computer that you want to use the
iostream standard library, which contains classes and functions written in the core
language. This header, specifically, allows you to manipulate input/output streams. After all this, you'll end up which
a temporary file that contains the expanded source code.
After the code is expanded, the compiler comes into play. The compiler takes the C++ code and converts this code into the assembly language, understood by the platform. You can see this in action if you head over to the Godbolt Compiler Explorer, which shows C++ being converted into assembly dynamically.
Third, the assembly code generated by the compiler is assembled into the object code for the platform. Essentially, this is when the compiler takes the assembly code and assembles it into machine code in a binary format. After researching this online, I figured out that a lot of compilers will allow you to stop compilation at this step. This would be useful for compiling each source code file separately. This saves time later if a single file changes - only that file needs to be recompiled.
Finally, the object code file generated by the assembler is linked together with the object code files for any library functions used to produce a shared library, dynamic library, or an executable file. It replaces all references to undefined symbols with the correct addresses.
That's all I have so far, folks! Hopefully this helps explain a little about the C++ compilation process. If you notice anything is incorrect, feel free to send me an email!