Compiling vs Running
What's the difference between compiling and running a program?
Compiling and running are two distinct steps in getting your program to work. Let's break this down:
Compiling
Compiling is like translating your C++ code into a language your computer understands:
// Your C++ code (human-readable)
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
}
The compiler converts this into machine code (not human-readable):
01001000 01100101 01101100 01101100 ...
Running
Running means actually executing the compiled program. Your computer:
- Loads the machine code into memory
- Follows the instructions
- Produces the output
The Complete Process
- Writing (You create
.cpp
files) - Compiling (Compiler creates
.exe
or similar) - Running (Computer executes the program)
Here's what can happen at each stage:
Compile-Time Errors
The following program is not valid C++. We forgot to include the semicolon, so the compiler cannot understand the code we wrote:
#include <iostream>
using namespace std;
int main() {
// won't compile!
cout << "Forgot semicolon"
}
error C2143: syntax error: missing ';' before '}'
Run-Time Errors
The following program has valid code so will compile successfully. However, the code includes an instruction to divide by zero, which will cause an error once we run the program:
#include <iostream>
using namespace std;
int main() {
// compiles but crashes when run!
cout << 100 / 0;
}
Successful Program
The following program will both compile and run successfully:
#include <iostream>
using namespace std;
int main() {
// compiles and runs fine
cout << "This works!";
}
This works!
Think of it like baking:
- Writing code is like writing a recipe
- Compiling is like gathering and preparing ingredients
- Running is like actually cooking the dish
You must successfully compile before you can run - just like you need ingredients before you can cook!
Setting up a C++ Development Environment
Getting our computer set up so we can create and build C++ programs. Then, creating our very first application