Skip to content
Theory · Your First Program · lesson 1 of 7

How a C++ program works

A C++ program is text, but the processor runs only machine code. That is why a program file cannot be run right away—it has to be translated first. Here is a program that prints one line:

C++
#include <iostream>

int main() {
    std::cout << "Hello, world\n";  // Hello, world
}

The line #include <iostream> inserts a description of the standard library's input and output tools into the file. Among them is std::cout, the program's standard output. The << operator sends text to it, and \n at the end of the text starts a new line.

Where execution starts

A program starts executing in the function main, and a program has exactly one. Its body consists of the statements inside the curly braces, and they run one by one, from top to bottom. The statement with std::cout ends with a semicolon. After the last statement of main, the program ends.

From text to program

The file hello.cpp that holds the program's text is called the source file. The compiler checks that the text follows the rules of C++ and translates it into machine code. It writes that code to an object file—for example, hello.o.

The linker joins the object files with ready-made code from the standard library, including the code of std::cout. The result is an executable file—the one the operating system runs. If there are several source files, the compiler translates each one separately, and the linker builds one program from them. Usually one command runs both steps, and the object files are only an intermediate result.

Errors before and after launch

If the text breaks the language rules, the compiler reports a compile error and names the line where it found the error. No executable file appears then, and there is nothing to run. But the compiler checks only the rules, not what the author meant. It lets the typo in "Helo, world\n" through, and the typo shows only at run time—in what the program prints.

Besides errors, the compiler issues warnings. A program with warnings still builds, but the compiler points at a place that looks like a mistake.

Common mistake

The semicolon after the statement with std::cout is missing:

C++
#include <iostream>

int main() {
    std::cout << "Hello, world\n"  // ✗
}
TEXT
error: expected ';' after expression

This is a compile error: no executable file appeared, so the program never ran.