Running Your First Program
Time for Rocket Run to say its first words. Five short lines of code and two terminal commands take you from an empty file to a program you can run. Every C++ program you ever write goes through the same small loop.
The rule
Write, compile, run: three steps, every time you change the code.
Create rocket.cpp:
#include <iostream>
int main() {
std::cout << "Rocket Run: ready for launch!\n";
return 0;
}Line by line:
#include <iostream>pulls in the part of the standard library that handles input and output.int main()is where every program starts. There must be exactly one.std::coutis the console output stream;std::says it lives in the standard library's namespace.<<sends text into it, and\nends the line.return 0;tells the operating system the program succeeded. Any other number signals a problem. (Inmainonly, leaving it out also means 0.)
Now compile and run:
g++ -std=c++20 -Wall -Wextra rocket.cpp -o rocket
./rocket-Wall -Wextra switch on helpful warnings, and -o rocket names the output file. On Windows the result is rocket.exe.
The shortcut
When the compiler complains, fix the first error first. One missing semicolon can confuse the compiler about everything after it, producing a pile of follow-on errors that vanish once the first is fixed.
The typo
You write
std::cout << "ready\n"and forget the;at the end.
The trap is forgetting the compile step. The executable is a separate file; editing rocket.cpp does not change it until you compile again.
Drills
Answer fast — trust the rule.
Where does a C++ program begin running?
You edit the message, run ./rocket, and see the old text. Why?
What does -o rocket do in the compile command?
The compiler prints 12 errors. What should you do first?
What does return 0; at the end of main communicate?
Remember
- Write, compile, run: three steps, every time you change the code.
- Shortcut: fix the first compiler error first, then recompile.
- Trap: editing the source does not change the executable until you compile.
