Program Execution Model

When one develops a C++ program, it does not run directly. Instead, it goes through a fixed sequence of steps before your computer actually understands and executes it.

Running Your Source Code

Let's start with a simple single-file C++ program. The following prints Hello World to the console.

main.cpp
#include <iostream>

int main() {
    std::cout << "Hello, world!";
    return 0;
}

This file is called the source code.

To run it, we need to compile the code:

clang++ main.cpp -o hello-world

This will produce an executable file called hello-world which your computer can finally run:

./hello-world

Each time you make changes to the source code, you will need to compile again.

What Just Happened ?!

Think of a compiler as a black box that simply converts source code to machine code.

chevron-rightWhat does a compiler exactly do?hashtag

This is beyond the scope of this workshop.

If you happen to be curious:

Compiling a C++ source code is usually a 4 step process. It composes of

a) Preprocessing where we substitute macros and header files with their actual content

b) Compilation from C++ to platform-specific assembly

c) Assemble where the resultant assembly code is assembled into actual object code

d) Linking to link external library functions that the executable needs

You can even pause the compilation process at each stage to inspect the immediate outputs using varying CLI flags.

Last updated

Was this helpful?