Running Your First Program
A C++ program starts at main, must be compiled into an executable after every change, and reports success to the operating system through its return value.
Follow one source file through compilation, linking and execution.
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.