Introduction and Environment Setup

Article · 3:00

What C++ is for, the four stages between your source file and a program, and getting a compiler working.

C++ is a compiled language. Your source is translated to machine code once, ahead of time, and what ships is an executable the processor runs directly. Python and JavaScript are interpreted - a program reads your source and acts on it while running. The difference is not academic: a compiled language has no interpreter sitting between your code and the processor, which is why C++ is chosen where the cost of that layer is unacceptable.

Where that matters in practice: game engines (Unreal is C++, and a frame has sixteen milliseconds), high-frequency trading, where the gap between a quote arriving and an order leaving is measured in microseconds, operating systems and browsers - Chrome, Windows and most of macOS's frameworks - and embedded systems, where there may be no operating system at all. The common thread is not just speed. It is predictability: no garbage collector deciding to run in the middle of your frame.

g++ main.cpp -o main looks like one action and is four. Naming them turns a confusing error into an obvious one, because each stage fails differently.

Preprocessing is text substitution. It expands every #include by pasting that whole header in, replaces every #define, and strips comments. Its output is still C++, and usually enormous - #include <iostream> alone brings in tens of thousands of lines. Compiling turns that expanded source into assembly, and this is the stage that reports syntax errors and type mismatches. Assembling turns assembly into machine code in an object file, one per source file, with references to other files left as placeholders. Linking joins the object files and libraries, resolving those placeholders into real addresses.

The distinction that saves the most time is between a compiler error and a linker error. error: 'cout' was not declared is a compiler error - a missing include or namespace. undefined reference to 'foo()' is a linker error - the header promised the compiler that foo exists, and the linker then could not find its body. One is a missing declaration; the other is a missing definition.

Installing a compiler. On Linux, sudo apt install build-essential gets you GCC. On macOS, xcode-select --install gets you Clang. On Windows you have three good options: Visual Studio 2022 with the "Desktop development with C++" workload for MSVC, MSYS2 for GCC, or WSL for the Linux toolchain. Any editor works - VS Code with the C/C++ extension, CLion, or Visual Studio itself.

// main.cpp - the anatomy of a C++ program.

#include <iostream>     // the preprocessor pastes this entire header in

int main()              // where execution begins. Exactly one of these.
{
    std::cout << "Hello, C++!" << std::endl;
    return 0;           // 0 means success, to whatever ran this
}

/*
  Reading that line by line:

  #include <iostream>
      Angle brackets search the compiler's own include paths; quotes
      ("myheader.h") search your project's directory first. iostream
      declares the stream objects - std::cout, std::cin, std::cerr.

  std::cout
      cout lives in the std namespace, so its full name is std::cout.
      The :: is the scope resolution operator. You will see tutorials
      write `using namespace std;` to avoid typing it - do not, outside
      of a tiny file. It drags every name in the standard library into
      your scope and you will eventually collide with one of them.

  <<
      The stream insertion operator. It is the left-shift operator,
      overloaded for streams - which is your first sight of the fact
      that in C++ operators are functions you can define.

  std::endl
      Writes a newline AND flushes the stream. In a loop that flush is
      expensive; prefer '\n' unless you need the flush.

  return 0;
      main is the only function allowed to omit this - fall off the end
      of main and 0 is returned for you. Be explicit anyway.
*/

// The four stages, run one at a time so you can see each output:
//
//   g++ -E main.cpp -o main.ii   // 1. preprocess - still C++, now huge
//   g++ -S main.ii -o main.s     // 2. compile    - assembly
//   g++ -c main.s -o main.o      // 3. assemble   - machine code
//   g++ main.o -o main           // 4. link       - a program
//
// All four at once, which is what you will normally type:
//
//   g++ -std=c++20 -Wall -Wextra -g main.cpp -o main
//
//   -std=c++20   pick the standard. Without it you get the compiler's
//                default, which may be years behind.
//   -Wall -Wextra  turn on the warnings. Most are real bugs.
//   -g           keep debug symbols so a debugger can name your lines.

Discussion

No questions on this topic yet. Sign in to ask the first one.