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

{% code title="main.cpp" %}

```cpp
#include <iostream>

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

{% endcode %}

This file is called the **source code.**

To run it, we need to compile the code:

{% code title="" %}

```sh
clang++ main.cpp -o hello-world
```

{% endcode %}

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

{% code title="" %}

```sh
./hello-world
```

{% endcode %}

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

<figure><img src="https://2807223923-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTUqAJOgHs57S8lmqdxRV%2Fuploads%2FVEdGvTX7WA5hCL21HmDx%2FScreenshot%202026-04-01%20at%202.03.33%E2%80%AFAM.png?alt=media&#x26;token=c39adfdc-15c7-4629-aa5a-a1a4e9b7a05e" alt=""><figcaption></figcaption></figure>

### What Just Happened ?!

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

<figure><img src="https://2807223923-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTUqAJOgHs57S8lmqdxRV%2Fuploads%2Fe8EScrWNrDdomYvEhRrL%2Fimage%20(1)%20(1).png?alt=media&#x26;token=266824d4-6122-4780-b0e0-62f8af4ba1ce" alt=""><figcaption><p>src: <a href="https://www.sitesbay.com/cpp/cpp-compiler">https://www.sitesbay.com/cpp/cpp-compiler</a></p></figcaption></figure>

<details>

<summary>What does a compiler exactly do?</summary>

This is beyond the scope of this workshop.

If you happen to be curious:

<figure><img src="https://2807223923-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTUqAJOgHs57S8lmqdxRV%2Fuploads%2FAKDdjqJJtAUe6Yl1bau0%2Fimage%20(1)%20(1)%20(1).png?alt=media&#x26;token=e7fd86c9-9d59-4a03-9c1c-2a1813a552b5" alt=""><figcaption><p>src: <a href="https://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html">https://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html</a></p></figcaption></figure>

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.

</details>
