Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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::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.

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.

A missing semicolonStep 1 of 4
  1. 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.

quick drill

Where does a C++ program begin running?

quick drill

You edit the message, run ./rocket, and see the old text. Why?

quick drill

What does -o rocket do in the compile command?

quick drill

The compiler prints 12 errors. What should you do first?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe launch message that would not change

You change Rocket Run's message from "ready" to "launching", run ./rocket, and still see "ready". Then, after a fix, the compiler prints 9 errors. Explain what went wrong the first time and how to approach the 9 errors.