$ g++ hello.cpp -o hellohello.cpp:3:26: error: expected ';'$ ./helloHello!# bugs can show up here$ ./helloHello!$ ./helloHello!hellostd libhello.o1#include <iostream>2int main() {3 std::cout << "Hello!\n";4 return 0;5}010101!
Violet card: the source code you write (hello.cpp)Sand blocks: the tools (preprocessor, compiler, linker); plum blocks: files of machine codeTokens: text hopping into the tools, machine code (01) hopping out, a red ! for an errorIn front: the source file hello.cpp, the preprocessor and the compiler. At the back: the object file hello.o, the standard library, the linker, the executable hello and the terminal. One command, g++ hello.cpp -o hello, runs the three tools in turn: text hops from the card into the preprocessor and the compiler, machine code comes out as hello.o, and the linker joins it with the library's code into the executable. Running ./hello prints Hello! in the terminal. A missing ; stops the build at the compiler: a compile error, so no program is made. The C++ standard describes nine phases of translation; the figure groups them into the three tools you meet in practice. One command such as g++ hello.cpp -o hello runs all three for you.

The source code

  1. You write a C++ program as plain text in a file, here hello.cpp. This is the source code: words and symbols a person can read. Your CPU cannot run this text directly.

Building

Running

What happens

;; step 1/9 · source
hello.cpp   the source file (.cpp is the usual ending)
  1  #include <iostream>
  2  int main() {
  3    std::cout << "Hello!\n";
  4    return 0;
  5  }
people read and write this; the CPU cannot run it as it is

The C++ standard describes nine phases of translation; the figure groups them into the three tools you meet in practice. One command such as g++ hello.cpp -o hello runs all three for you. File names differ between systems: object files end in .o on Linux and macOS and .obj on Windows, and the executable is hello.exe on Windows. On Windows with Microsoft's compiler the command is cl /EHsc hello.cpp.