Life of a C++ Program
in Fall 2020 on C++, Programming Basics
How does our high-level program gets translated and performed by our computer?
1. Editing
- Input: None
- Output:
hello.cpp
A C++ program is essentially ‘born’ in a text editor where we write our code and save it as hello.cpp
:
// our hello world program
#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl;
return 0;
}
2. Preprocessing
- Input:
hello.cpp
- Output:
hello.i
In exploring the anatomy of C++ program, we became familiar with the purpose of the preprocessor. The preprocessor handles all directives (which are all the #include
s). For example, the iostream
file is taken from storage and placed into the hello.i
with the original content of the hello.cpp
file. The below hello.i
file is the output of the preprocessor.
Note: To derive the hello.i
file on your machine, use the g++ -E hello.cpp -o hello.i
command.
Compilation
- Input:
hello.i
- Output:
hello.s
When a program is compiled, it is converted to assembly code which is the middle ground between human-understandable code (such as C++) and machine-understandable code (binary).
Note: To derive the hello.s
file on your machine, use the g++ -S hello.i -o hello.s
command.
Assemble
- Input:
hello.s
- Output:
hello.o
For the computer to understand your C++ program, it must be converted to binary code. The final output is an object file (later detailed in the Linking section).
Note: To derive the hello.o
file on your machine, use the g++ -c hello.s -o hello.o
command.
Linking
- Input:
hello.o
- Output:
hello
The output of the Assemble stage are object files that correspond to content of the .cpp
file. These object files are in machine language, but cannot yet be executed. Linking creates an executable file (.exe
) from the object files. The command to link the assembly object files is g++ hello.o -o hello
. The hello
file will look like the assembly object file because it is also in binary.
Execution
Executing or running the hello
file will print in the console Hello World
. The command for execution is .\hello