CS107E Week 2: From Expressing Intent in C to Builds and Bare-Metal Execution

Over the past few days, I have been tracing execution downward: from the intent expressed in C, through the machine instructions defined by the ISA, to the CPU’s control and data paths. How does a program actually execute?

Reading the Week 2 slides today helped me reconnect those layers. Five questions run through the material: Why do we need C? How does C become machine instructions? How is compilation different from execution? How do we organize a build as the number of files grows? And how can a C program run without an operating system?

Together, these questions explain how a piece of C written on my computer passes through a toolchain and eventually produces real hardware behavior on the MangoPi.

1. If assembly can control the CPU, why do we need C?

Assembly closely reflects the operations a machine provides. When writing programs, however, people find it easier to organize ideas with variables, expressions, conditions, loops, and functions. C offers a more convenient language for expressing that intent, while the compiler chooses how to implement it with instructions for the target machine.

Expression in CPossible lower-level operations
Addition, bitwise operations, and other expressionsALU operations
Access to variables and arraysRegister operations and, when needed, loads and stores
if, while, and forConditions and branches that determine where the PC points next
Function callsPassing arguments, saving necessary state, jumping, and returning according to a calling convention

These correspondences help explain the connection; they are not word-for-word translations. A piece of C may expand into several instructions, or optimization may combine or even eliminate it.

I can initially follow the CPU’s work along two lines: computation and data movement determine how data changes; sequential execution, branches, and jumps update the PC to determine where execution goes next. C makes behavior easier for people to describe, and the compiler turns that description into an executable form.

2. How does C become a program the MangoPi can execute?

The first distinction is that the computer running the build tools and the machine that will run the resulting program are two separate things.

I develop on a Mac but want the program to execute on the MangoPi’s RISC-V CPU, so I need a cross-toolchain targeting that platform. Producing code that merely runs on the Mac is not enough. Instructions must conform to the target CPU’s ISA, and the program must also meet the target platform’s ABI, link layout, and execution-environment requirements. The ISA defines instructions and architectural state; the ABI adds conventions for matters such as passing arguments and return values through registers and the stack.

First, separate the build into stages:

C source code: main.c
    ↓ compiler
Assembly: main.s
    ↓ assembler
Object file: main.o
    ↓ linker + other object files / libraries
Final program

The compiler translates C into a lower-level representation. The assembler encodes assembly instructions into an object file. The linker combines object files and required libraries, resolving symbol references and laying out addresses. In practice, a compiler driver may invoke several of these tools for us, and not every stage necessarily leaves a separate file behind.

The compiler, assembler, and linker are tools used to build a program; they are not components inside the CPU. Only after a download or loading tool places the resulting program on the MangoPi does the target CPU execute it:

Final program
    ↓ download / loader
MangoPi CPU
    ↓ registers / ALU / PC
Memory and memory-mapped I/O
    ↓ peripheral control
GPIO output levels

This completes the path from variables and loops in the human world of abstractions to data movement and changes in electrical levels in hardware.

3. What is known at compile time, and what is known at runtime?

Once the toolchain is clear, there is a distinction in time to make: compile time is when the build tools process the program; runtime is when the generated program actually executes. In this cross-development setup, the former takes place on the development computer and the latter on the MangoPi.

For example:

int x = 2 * 3;

The compiler already knows both operands, so it may calculate 6 in advance. This is called constant folding. For understanding, we can think of it as:

int x = 6;

The actual machine code may not retain a variable named x, but it does not need to calculate 2 × 3 again at runtime solely for this expression.

The boundary changes with this statement:

int x = a * 3;

If a is only available at runtime, the compiler generally cannot determine the final result in advance. It needs to generate code that computes a result from a. Even then, the machine code does not necessarily contain a multiplication instruction: the compiler may choose an equivalent implementation.

What I need to distinguish is that whether the answer can be known in advance and which instructions implement the computation are two different questions.

4. How does Make organize a growing build?

With one source file, I can invoke the tools manually. As the number of files grows, the questions become: which outputs depend on which inputs? After editing a file, which steps need to be repeated, and which results can be reused?

Make uses rules in a Makefile to decide whether targets need updating and then executes the corresponding commands. The Makefile describes dependencies and build methods, Make schedules the necessary steps, and tools such as the compiler, assembler, and linker perform their respective jobs.

A rule has this basic structure:

target: prerequisites
	command

In other words: “What do I want to produce, what does it depend on, and which command produces it when needed?” In an actual Makefile, a recipe command normally begins with a Tab.

Suppose program depends on main.o and gpio.o, and each object file comes from its corresponding C source:

          program
          /     \
      main.o   gpio.o
        |        |
      main.c   gpio.c

Editing only gpio.c usually requires regenerating gpio.o and relinking program. If main.c and the other prerequisites of main.o have not changed, main.o can be reused. That is the value of an incremental build.

How does Make decide that a target is out of date? For ordinary file dependencies, the basic rule is: if the target does not exist, or a prerequisite has a newer modification time than the target, the target needs to be regenerated. Make does not usually compare file contents directly.

For example, if gpio.c was modified at 10:05 but gpio.o was generated at 10:00, Make considers gpio.o out of date. Conversely, if gpio.o is newer and no other prerequisite triggers a rebuild, it can be reused. This depends on the Makefile listing dependencies correctly; real projects may also need to track header files.

Writing nearly identical compilation rules for every .c file would be repetitive. A pattern rule combines them into a general form:

CC = cc

program: main.o gpio.o
	$(CC) -o $@ $^

%.o: %.c
	$(CC) -c $< -o $@

Here, %.o: %.c means that a .c file can be turned into its corresponding .o using the same method. $@ is the target name, $< is the first prerequisite, and $^ is the list of all prerequisites. This example uses an ordinary cc to illustrate the structure. A MangoPi project needs the course’s configured cross-toolchain, compilation flags, and linker configuration.

Make manages the build process. It does not execute the final program as the target CPU does, or interpret C semantics on the compiler’s behalf.

5. What lets a C program run without an operating system?

After understanding how the program is built, the final question is where it runs and what it relies on. An ordinary Mac application and a MangoPi bare-metal program use C but depend on different execution environments.

On a Mac, I might write:

#include <stdio.h>

int main(void)
{
    printf("hello\n");
    return 0;
}

What I see is main starting, a call to printf, and the program ending. Behind that are startup code, a runtime, the standard library, and an operating system. printf writes formatted output to standard output, whose destination may be a terminal or may be redirected. The execution environment provides these facilities together; the CPU does not inherently know how to display “hello” on a screen.

This helps me understand a hosted environment: a program runs within an environment that provides the corresponding libraries and execution facilities. By comparison, a MangoPi bare-metal program has no operating system managing those services and is closer to a freestanding environment.

The absence of an operating system does not prevent the CPU from executing machine instructions. What changes is that the facilities previously supplied by the execution environment must now be prepared by us, course support code, or other low-level components.

For example, there must be concrete implementations for where execution starts, how the stack is set up, how necessary state is initialized, and where output goes. Bare-metal software can implement functionality such as printf, but it does not automatically have the Mac’s terminal and standard-output facilities. Output may need to be connected to a device such as a UART.

Mac application:
C program → runtime / libraries → OS → hardware

MangoPi bare-metal program:
C program → startup / support code / drivers → hardware

The key difference is therefore what the program can rely on at runtime and who supplies the missing pieces, rather than C being able to run in one environment but not the other. The built program still needs to be placed on the board using the course’s xfel or another loading tool before execution begins on the target machine.

Connecting Week 2 into one picture

I can now connect the process: C expresses my intent; a cross-toolchain generates a program for the target platform; Make organizes the build according to dependencies; a loading tool sends the program to the board; startup and support code prepare the execution conditions; and the CPU executes instructions according to the ISA, producing effects through memory and peripherals.

What became clearer today are three boundaries: expressing intent versus executing instructions, building a program versus running it, and the language itself versus the facilities supplied by its execution environment.

Further reading: Rules in GNU Make, GNU Make pattern rules, and GCC on hosted and freestanding environments.