Skip to the workspace
Pebellslearn by building
Setting Up Your Environment  ›  Capstone Project

Running Your First Program

Running your First Program 12 minA 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.

cpp / Running Your First Program

Explore each scene at your own pace.

01 · The rule

The rule

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::cout is the console output stream; std:: says it lives in the standard library's namespace. << sends text into it, and \n ends the line.
  • return 0; tells the operating system the program succeeded. Any other number signals a problem. (In main only, 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.