学习日志
CS107E Week 2:从 C 的表达,到构建与裸机运行
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 C | Possible lower-level operations |
|---|---|
| Addition, bitwise operations, and other expressions | ALU operations |
| Access to variables and arrays | Register operations and, when needed, loads and stores |
| if, while, and for | Conditions and branches that determine where the PC points next |
| Function calls | Passing 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 programThe 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 levelsThis 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
commandIn 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.cEditing 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 → hardwareThe 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.
前几天,我一直在往下追问:从 C 语言表达的意图,到 ISA 规定的机器指令,再到 CPU 内部的控制通路和数据通路,程序究竟是怎样执行的?
今天看 Week 2 的 slides,我开始把这些层次重新串起来。这一周的内容可以用五个问题贯穿:为什么需要 C?C 怎样变成机器指令?编译和运行有什么区别?文件多起来后怎样组织构建?没有操作系统,C 程序又靠什么运行?
它们共同回答的是:我在电脑上写下的一段 C,怎样经过工具链,最终在 MangoPi 上产生真实的硬件行为。
一、已经能用汇编控制 CPU,为什么还需要 C?
汇编贴近机器提供的操作,但人写程序时,更习惯用变量、表达式、条件、循环和函数来组织想法。C 提供了更方便表达这些意图的一层语言,再由编译器选择如何把它们落实为目标机器的指令。
| C 中的表达 | 可能对应的底层操作 |
|---|---|
| 加法、按位运算等表达式 | ALU 运算 |
| 变量、数组的数据访问 | 寄存器操作,必要时 load / store |
| if、while、for | 条件判断和分支,决定 PC 接下来指向哪里 |
| 函数调用 | 按调用约定传递参数、保存必要状态、跳转和返回 |
这些是帮助理解的对应关系,并非逐字翻译。一段 C 可能被展开为多条指令,也可能因优化而合并甚至消失。
我可以把 CPU 的工作先抓成两条线:数据怎么变化,靠运算和数据传送;程序下一步去哪,靠顺序执行、分支和跳转来更新 PC。 C 让人更容易描述行为,编译器负责把这种描述变成机器能执行的形式。
二、C 怎样变成 MangoPi 能执行的程序?
这里先要区分:编译工具运行在哪台电脑上,与它生成的程序要在哪台机器上运行,是两件事。
我在 Mac 上开发,却希望程序在 MangoPi 的 RISC-V CPU 上执行,因此要使用面向目标平台的交叉工具链。它生成的不能只是“Mac 能运行的代码”。指令必须符合目标 CPU 的 ISA,程序还需要满足目标平台的 ABI、链接布局和运行环境要求。ISA 规定指令及架构状态,ABI 则进一步约定参数、返回值等如何使用寄存器和栈。
先把构建过程拆开看:
C source code: main.c
↓ compiler
Assembly: main.s
↓ assembler
Object file: main.o
↓ linker + other object files / libraries
Final programcompiler 负责把 C 翻译到更低层的表示;assembler 把汇编指令编码成目标文件;linker 把多个目标文件和所需库组合起来,处理符号引用和地址布局。实际使用时,编译器驱动程序可能替我们调用其中多个工具,不一定每一步都留下独立文件。
compiler、assembler、linker 是构建程序的工具,并不是 CPU 内部的组成部分。 生成的程序经下载或加载工具放到 MangoPi 上后,才由目标 CPU 执行:
Final program
↓ download / loader
MangoPi CPU
↓ registers / ALU / PC
Memory and memory-mapped I/O
↓ peripheral control
GPIO output levels这样,从人类抽象世界里的变量和循环,到硬件上的数据流动与电平变化,才连成了一条完整的路径。
三、编译期和运行期,分别知道什么?
理解工具链之后,再看一个时间上的区别:编译期是构建工具处理程序的时候;运行期是生成的程序真正执行的时候。 对这次交叉开发来说,前者发生在开发电脑上,后者发生在 MangoPi 上。
比如:
int x = 2 * 3;编译器已经知道两个操作数,就可能提前算出 6。这叫常量折叠(constant folding)。为了理解,可以把它想成:
int x = 6;实际机器代码未必保留变量 x,但不需要仅为了这个表达式,在运行时再计算一次 2 × 3。
换成下面这一句,边界就不同了:
int x = a * 3;如果 a 只能在运行时获得,编译器通常不能提前确定最终结果,需要生成根据 a 计算结果的代码。不过,这也不意味着机器代码里一定会出现一条乘法指令:编译器仍可能选择其他等价实现。
我真正需要区分的是:答案能否提前确定,以及最终用什么指令实现,是两个层面的问题。
四、文件越来越多,Make 怎样组织构建?
只有一个文件时,我可以手动调用工具。文件变多之后,问题变成了:哪些产物依赖哪些输入?修改一个文件后,哪些步骤必须重做,哪些可以沿用?
Make 根据 Makefile 中的规则,判断目标是否需要更新,然后执行对应命令。Makefile 描述依赖关系和构建方法,Make 安排需要进行的步骤,compiler、assembler、linker 等工具完成各自的工作。
一条规则的基本结构是:
target: prerequisites
command也就是:“我要生成什么,它依赖什么,需要时用什么命令生成。”实际 Makefile 中,命令行通常要以 Tab 开头。
假设 program 依赖 main.o 和 gpio.o,而两个目标文件分别来自对应的 C 文件:
program
/ \
main.o gpio.o
| |
main.c gpio.c只修改 gpio.c 时,通常需要重新生成 gpio.o,再重新链接 program;如果 main.c 及 main.o 的其他依赖没有变化,main.o 就可以继续使用。这就是增量构建的价值。
那 Make 怎么判断“过期”?对普通文件依赖,基本规则是:目标不存在,或者某个依赖文件的修改时间比目标更新,就需要重新生成目标。 它通常不是直接比较文件内容。
例如 gpio.c 在 10:05 修改,而 gpio.o 生成于 10:00,Make 会判断 gpio.o 需要更新。反过来,如果 gpio.o 更新,并且其他依赖也没有触发重建,它就可以被沿用。前提是 Makefile 正确列出了依赖;真实项目还可能需要跟踪头文件。
如果每个 .c 都要写一条几乎相同的编译规则,就太重复了。模式规则(pattern rule)把它们合并成通用写法:
CC = cc
program: main.o gpio.o
$(CC) -o $@ $^
%.o: %.c
$(CC) -c $< -o $@这里,%.o: %.c 表示用相同方法把某个 .c 生成对应的 .o;$@ 是目标名,$< 是第一个依赖,$^ 是全部依赖。上面用普通 cc 展示结构;MangoPi 项目要使用课程配置的交叉工具链、编译参数和链接配置。
Make 管理的是构建过程。它不会像目标 CPU 那样执行最终程序,也不会替编译器理解 C 的语义。
五、没有操作系统,C 程序靠什么运行?
把“怎么构建”理清之后,最后一个问题是“在哪里、靠什么运行”。同样是 C,Mac 上的普通应用与 MangoPi 裸机程序所依赖的环境不同。
在 Mac 上写:
#include <stdio.h>
int main(void)
{
printf("hello\n");
return 0;
}我看到的是 main 开始、调用 printf、程序结束。但程序背后还有启动代码、运行时、标准库和操作系统。printf 将格式化结果写到标准输出,最终去向可能是终端,也可能被重定向;这些设施由运行环境共同提供,并不是 CPU 天生就知道“把 hello 显示到屏幕上”。
这可以帮助我理解 hosted environment:程序运行在提供相应库和运行设施的环境里。与之相比,MangoPi 的裸机程序没有操作系统替它管理这些服务,更接近 freestanding environment。
没有操作系统,不妨碍 CPU 执行机器指令;改变的是,原来由运行环境提供的那些设施,现在需要由我们、课程支持代码或其他底层组件来准备。
例如,程序从哪里开始执行、如何设置栈、怎样初始化必要状态,以及输出设备在哪里,都需要有具体实现。裸机上也可以实现 printf 一类功能,但它不会自动拥有 Mac 上的终端和标准输出设施;输出可能需要接到 UART 等设备上。
Mac application:
C program → runtime / libraries → OS → hardware
MangoPi bare-metal program:
C program → startup / support code / drivers → hardware因此,两者的关键差别,不是“C 在一边能运行、在另一边不能运行”,而是程序运行时能够依赖什么,以及缺少的部分由谁提供。构建好的程序仍需经课程使用的 xfel 或其他加载工具放到板子上,然后才进入目标机器的执行过程。
把 Week 2 连成一张图
现在我可以把它串起来:C 帮我表达意图;交叉工具链面向目标平台生成程序;Make 根据依赖组织构建;加载工具把程序送到板子;启动与支持代码准备运行条件;最后,CPU 按 ISA 执行指令,并通过内存和外设产生实际效果。
今天真正理清的是三条边界:表达意图与执行指令的边界,构建程序与运行程序的边界,以及语言本身与运行环境所提供设施的边界。
延伸阅读:GNU Make 的规则、GNU Make 模式规则、GCC 对 hosted 与 freestanding 环境的说明。