OSTEP:Laboratory Tutorial
OSTEP:Laboratory Tutorial
本篇对应 OSTEP Version 1.10 的 Appendix F “Laboratory: Tutorial”。它是进入 UNIX/C systems programming projects 的实践前置材料。
类型与定位
- 笔记类型:实验教程翻译/知识整理
- 翻译基准:官方 Laboratory: Tutorial
- 保真约定:按原文 F.1–F.9 的顺序翻译;命令、C code、Makefile、gdb transcript、option、路径和 API 保留原样。
- 图件说明:原文没有独立 raster image;编译流水线使用 Mermaid 表示,代码和 terminal transcript 使用 code block 保留。
- 实验口径:教程中的命令示例不等于已执行;“实验执行记录”只记录真实 command、output 和环境限制。
TL;DR
这是一份非常简短的 UNIX systems C programming environment 入门。它不全面,也不会特别详细,只是希望足够让你开始动手。
想成为 expert programmer,不能只掌握一门 language 的 syntax。你还需要了解自己的 tools、libraries 和 documentation。与 C compilation 相关的 tools 是 gcc、gdb,也可能包括 ld;大量 library routines 已经可用,其中很多功能包含在 libc 中,而 libc 默认会链接到所有 C programs。知道如何找到所需的 library routines——例如学会查找和阅读 man pages——也是值得获得的技能。
在这些领域成为 expert 需要时间,和生活中几乎所有值得做的事情一样。提前花时间了解 tools 和 environment,绝对值得。
目录
| 章节 | 内容 |
|---|---|
| TL;DR | 教程范围与 systems programmer 的工具观 |
| F.1 一个简单的 C 程序 | include、main()、argc/argv 与退出状态 |
| F.2 编译与执行 | gcc driver 与 compilation pipeline |
| F.3 有用的 flags | -o、-Wall、-g、-O |
| F.4 与 libraries linking | man page、-l、static/dynamic linking、-I/-L |
| F.5 Separate Compilation | object files、link line 与增量编译 |
| F.6 Makefiles | rules、dependencies、timestamp 与 variables |
| F.7 Debugging | gdb、segmentation fault、breakpoint、step |
| F.8 Documentation | man pages、errno、preprocessor 与 info |
| F.9 推荐阅读 | C、make、GDB、UNIX 与 expert C 读物 |
| 实验执行记录 | 本机真实 build、运行与环境限制 |
F.1 一个简单的 C 程序
从一个简单的 C program 开始,假设保存在 hw.c 中。和 Java 不同,file name 与 file contents 不一定存在对应关系;因此,应该用 common sense 给 files 取合适的名字。
第一行指定要 include 的 file,这里是 stdio.h。它为许多常用的 input/output routines 提供 prototypes,我们关心的是 printf()。使用 #include directive 时,就是告诉 C preprocessor(cpp)找到指定的 file(例如 stdio.h),并在 #include 所在位置直接插入它。默认情况下,cpp 会到 /usr/include/ 中寻找该 file。
接下来是 main() routine 的 signature:它返回一个 integer(int),并接收两个 arguments——一个 integer argc,表示 command line argument 的数量;以及一个 character pointer array(argv),其中每个 pointer 指向 command line 中的一个 word,最后一个元素是 null。关于 pointers 和 arrays,后文还会继续介绍。
/* header files go up here */
/* note that C comments are enclosed within a slash and
a star, and may wrap over lines */
// two slashes work too (and may be preferred)
#include <stdio.h>
// main returns an integer
int main(int argc, char *argv[]) {
/* printf is our output function;
by default, writes to standard out */
/* printf returns an integer, but we ignore that */
printf("hello, world\n");
/* return 0 to indicate all went well */
return(0);
}
这个 program 只打印字符串 hello, world,并由于 printf() 调用末尾的反斜杠加 n,把 output stream 推进到下一行。随后,program 返回一个 value;这个 value 会传回执行该 program 的 shell。script 或 terminal 上的 user 可以检查这个 value(在 csh 和 tcsh shells 中,它保存在 status variable 中),判断 program 是 cleanly 退出还是带着 error 退出。
F.2 编译与执行
下面使用 gcc 作为例子;在某些 platforms 上,也可以使用其他 native compiler,例如 cc。
prompt> gcc hw.c
gcc 严格来说不是 compiler,而是一个叫作 compiler driver 的 program,因此它负责协调 compilation 的多个步骤。通常会有四到五个步骤:
gcc运行cpp(C preprocessor),处理#define和#include等 directives。产物仍是 source code,也就是一个 C file。- 真正的 compilation 开始,通常由名为
cc1的 command 完成。它把 source-level C code 转换成针对 host machine 的 low-level assembly code。 - 执行 assembler
as,生成 object code,也就是 machines 真正能够理解的 bits and things。 - 最后由 link-editor(或 linker)
ld把一切组合成 final executable program。
flowchart LR
A[.c source] --> B[cpp preprocessor]
B --> C[cc1 compiler]
C --> D[as assembler]
D --> E[.o object]
E --> F[ld linker]
F --> G[executable]
幸运的是,在大多数情况下,你可以放心地不了解 gcc 的内部工作方式,只需要配合正确的 flags 使用它。
上面的 compilation 默认生成名为 a.out 的 executable:
prompt> ./a.out
运行时,OS 会正确设置 argc 和 argv。具体来说,argc 等于 1,argv[0] 是字符串 "./a.out",argv[1] 是 null,表示 array 的结束。
F.3 有用的 flags
在继续学习 C language 之前,我们先指出一些对 gcc 有用的 compilation flags。
prompt> gcc -o hw hw.c # -o: to specify the executable name
prompt> gcc -Wall hw.c # -Wall: gives much better warnings
prompt> gcc -g hw.c # -g: to enable debugging with gdb
prompt> gcc -O hw.c # -O: to turn on optimization
这些 flags 可以自由组合,例如:
prompt> gcc -o hw -g -Wall hw.c
其中,应该始终使用 -Wall。它会针对可能的 mistakes 给出大量额外 warnings。不要忽略 warnings;应该修复它们,让这些 warnings 消失。
调试时,通常需要对每个 compile line 加上 -g,以便把 debugging information 放进 executable;同时不要打开 -O,因为 optimization 可能让 source-level debugging 变得 confusing。
F.4 与 libraries linking
有时需要在 program 中使用 library routine。由于大量 routines 已经在 C library 中,而 C library 会自动链接到每个 program,通常只需要找到正确的 #include file。最好的办法是查看 manual pages,也就是通常所说的 man pages。
例如,假设要使用 fork() system call。在 shell prompt 输入 man fork,就会得到关于 fork() 工作方式的文字说明。页面最顶部通常有一小段 code snippet,告诉你需要 include 哪些 files 才能编译。在 fork() 的例子中,需要 include unistd.h:
#include <unistd.h>
注:
fork()是 system call,而不只是 library routine。不过,C library 为所有 system calls 提供 C wrappers;这些 wrappers 只负责 trap 进入 operating system。
有些 library routines 不在 C library 中,因此需要多做一点工作。例如,math library 提供 sines、cosines、tangents 等 routine。若要使用 tan(),仍然先检查 man page。Linux man page 顶部会显示:
#include <math.h>
...
Link with -lm.
第一行表示需要 include math library,它位于 filesystem 的标准位置 /usr/include/math.h。第二行说明如何将 program 与 math library “link”起来。许多 useful libraries 位于 /usr/lib,math library 就在那里。
libraries 有两类:以 .a 结尾的 statically-linked libraries,以及以 .so 结尾的 dynamically-linked libraries。static library 会被直接合并进 executable;linker 把 library 的 low-level code 插入 executable,因此 binary object 会更大。dynamic linking 则只把 library 的 reference 放入 program executable;运行 program 时,由 OS loader 动态 link library。
相比 static approach,dynamic linking 通常更受偏好,因为它节省 disk space,并允许多个 applications 在 memory 中共享 library code 和 static data。对于 math library,static 版本是 /usr/lib/libm.a,dynamic 版本是 /usr/lib/libm.so。
prompt> gcc -o hw hw.c -Wall -lm
-lXXX flag 告诉 linker 查找 libXXX.so 或 libXXX.a,通常按这个顺序查找。如果确实想优先使用 static library,还可以使用另一个 flag;可自行查阅 documentation。有人偏好 static library,是因为 dynamic libraries 会带来轻微的 performance cost。
如果希望 compiler 在通常位置之外搜索 headers,或链接指定的 libraries:
-I/foo/bar # 在 /foo/bar 中查找 headers
-L/foo/bar # 在 /foo/bar 中查找 libraries
UNIX 中的 .(dot)表示 current directory。注意:-I 应放在 compile line,-L 应放在 link line。
F.5 Separate Compilation
program 足够大以后,可以将它拆分到不同 files 中,分别编译,再 link 到一起:
# we are using -Wall for warnings, -O for optimization
prompt> gcc -Wall -O -c hw.c
prompt> gcc -Wall -O -c helper.c
prompt> gcc -o hw hw.o helper.o -lm
-c flag 告诉 compiler 只生成 object file;这里会生成 hw.o 和 helper.o。它们不是 executables,而只是各自 source file 中 code 的 machine-level representation。由于输入 files 是 .o 而不是 .c,gcc 会跳过前面的 compilation steps,直接调用 link-editor ld,将它们 link 成一个 executable。
第三行通常称为 link line,需要在这里指定 -lm 等 link-specific commands。类似地,-Wall 和 -O 只在 compile phase 需要,因此不必出现在 link line 上。
当然,也可以把所有 C source files 一次交给 gcc:
prompt> gcc -Wall -O -o hw hw.c helper.c
但这种方式每次都要重新编译所有 source-code files,可能很耗时。分别编译后,只需重新编译 editing 期间发生变化的 files,从而提高 productivity;这个过程最好交给 make 管理。
F.6 Makefiles
make 可以自动化大量 build process,因此对于 serious program 和 programmer 都是极其重要的 tool。下面是保存为 Makefile 的简单例子:
hw: hw.o helper.o
gcc -o hw hw.o helper.o -lm
hw.o: hw.c
gcc -O -Wall -c hw.c
helper.o: helper.c
gcc -O -Wall -c helper.c
clean:
rm -f hw.o helper.o hw
它默认寻找 Makefile 或 makefile 作为 input;也可以用 flag 指定其他 makefile。GNU 版本的 make 叫 gmake,功能比 traditional make 更完整;在 Linux systems 上,gmake 和 make 是同一个东西。
Makefiles 基于 rules。一般形式:
target: prerequisite1 prerequisite2 ...
command1
command2
...
- target 通常是 command 生成的 file name,例如 executable 或 object file;也可以是 action 名称,例如
clean。 - prerequisite 是创建 target 时使用的 input file,一个 target 通常依赖多个 files。
- command 是
make执行的 action;一个 rule 可以有多个 commands,每个 command 独占一行。
重要:每个 command line 开头必须是一个真正的 tab character!如果只使用 spaces,make 会打印 obscure error message 并退出。
通常,带有 prerequisites 的 rule 中的 command 用来在某个 prerequisite 发生变化时创建 target file。不过,为 target 指定 commands 的 rule 不一定要有 prerequisites;例如,本例中与 clean target 关联的 delete command 就没有 prerequisites。
执行例子的 make 时,make 先处理 hw 的 prerequisites hw.o 和 helper.o,再递归检查各自的 source。若 hw.c 的 modification time 晚于 hw.o 的 creation time,或 hw.o 根本不存在,就执行 gcc -O -Wall -c hw.c;helper.o 同理。两个 object files 准备好后,再执行 gcc -o hw hw.o helper.o -lm。
clean 没有 prerequisites,必须显式请求:
prompt> make clean
它会删除 object files 和 executable,适合从头 rebuild。
使用 variables 和 pattern rule 的更通用写法:
# specify all source files here
SRCS = hw.c helper.c
# specify target here (name of executable)
TARG = hw
# specify compiler, compile flags, and needed libs
CC = gcc
OPTS = -Wall -O
LIBS = -lm
# this translates .c files in src list to .o’s
OBJS = $(SRCS:.c=.o)
# all is not really needed, but is used to generate the target
all: $(TARG)
# this generates the target executable
$(TARG): $(OBJS)
$(CC) -o $(TARG) $(OBJS) $(LIBS)
# this is a generic rule for .o files
%.o: %.c
$(CC) $(OPTS) -c $< -o $@
# and finally, a clean line
clean:
rm -f $(OBJS) $(TARG)
它允许通过修改 SRCS 添加 source files,通过 TARG 改变 executable name,也能集中修改 compiler、flags 和 libraries。大型、复杂 program 的 prerequisites 不一定容易确定,可以进一步了解 makedepend。
F.7 Debugging
建立良好的 build environment 并正确编译 program 后,仍可能有 bugs。只靠努力思考有时有效,但经常无效,因为缺少 information:你不知道 program 内部究竟发生了什么。GNU debugger gdb 可以提供帮助。
#include <stdio.h>
struct Data {
int x;
};
int
main(int argc, char *argv[])
{
struct Data *p = NULL;
printf("%d\n", p->x);
}
这里 main dereference 了为 NULL 的 p,会产生 segmentation fault。开始 debugging session 前,给每个 compile line 加上 -g,并不要打开 optimization(-O),否则 source-level debugging 可能 confusing。
这个例子中的问题通过直接检查就很容易修复;不过在更复杂的 program 中,找到这类问题并不总是容易。
prompt> gdb buggy
GNU gdb ...
Copyright 2008 Free Software Foundation, Inc.
(gdb)
(gdb) run
Starting program: buggy
Program received signal SIGSEGV, Segmentation fault.
0x8048433 in main (argc=1, argv=0xbffff844) at buggy.c:19
19 printf("%d\n", p->x);
(gdb) print p
$1 = (Data *) 0x0
gdb 会指出 segmentation fault 发生的位置;print 能显示 p 是 Data struct pointer,当前为 NULL,也就是 0x0。
还可以设置 breakpoint,并逐行推进:
(gdb) break main
Breakpoint 1 at 0x8048426: file buggy.c, line 17.
(gdb) run
Starting program: /homes/hacker/buggy
Breakpoint 1, main (argc=1, argv=0xbffff844) at buggy.c:17
17 struct Data *p = NULL;
(gdb) next
19 printf("%d\n", p->x);
(gdb) next
Program received signal SIGSEGV, Segmentation fault.
0x8048433 in main (argc=1, argv=0xbffff844) at buggy.c:19
19 printf("%d\n", p->x);
next 执行下一条 source-level command;step 也是推进 program 的方式。还可以检查 core files,或 attach 到已运行的 program。这个简短介绍没有覆盖 gdb 的丰富功能,应继续阅读 documentation。²
上面的讨论远不足以展现 gdb 的全部能力;它是一个丰富而灵活的 debugging tool,功能远多于这里有限篇幅能够介绍的内容。请在自己大量的 spare time 中继续阅读相关资料,成为 gdb expert。
² 在 gdb debugging session 中,还可以使用交互式的 help command;更多细节应查阅 documentation。
F.8 Documentation
需要进一步了解这些 tools,就要使用它们并自行阅读 documentation。可以查看:
prompt> man gcc
prompt> man gmake
prompt> man gdb
也可以用 man -k 按 keyword 搜索,不过它有时不如预期;Google 可能更好。
如果多个东西都叫 XXX,man XXX 不一定得到想要的页面。例如 man kill 默认可能得到 command-line program,而不是 kill() system call。man pages 按 sections 划分;默认返回找到的最低 section。看到 kill(2) 就说明进入了 system calls 所在的 Section 2;man man 可了解各 section,man -a kill 可依次查看所有同名页面。
man pages 常用于查 arguments、header files 和 linking requirements。比如 open():
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *path, int oflag, /* mode_t mode */...);
它说明所需 headers、path、oflag 和 optional mode argument。如果需要链接 library,也会在这里说明。
特别有用的是 RETURN VALUES section:
RETURN VALUES
Upon successful completion, the open() function opens the
file and return a non-negative integer representing the
lowest numbered unused file descriptor. Otherwise, -1 is
returned, errno is set to indicate the error, and no files
are created or modified.
因此可以通过 return value 判断 open 是否成功;失败时,open 和许多 standard library routines 会设置 global variable errno,具体 error 见 ERRORS section。
要有效使用 man pages,需要付出一些 effort。它们通常分成若干标准 sections,主体部分会说明如何传入不同 parameters,使 function 以不同方式工作。
另一个常常需要查找的内容,是 man page 本身没有给出的 structure definition。例如,gettimeofday() 的 synopsis 可能是:
SYNOPSIS
#include <sys/time.h>
int gettimeofday(struct timeval *restrict tp,
void *restrict tzp);
从这里可以看出,时间会写入一个名为 timeval 的 structure,但 man page 不一定告诉你这个 struct 包含哪些 fields(本例中会告诉你,但你不总是这么幸运)。因此,你可能需要自己寻找它。
如果需要寻找 man page 未给出的 struct definition,例如 gettimeofday() 的 timeval,可以先搜索 /usr/include:
prompt> grep 'struct timeval' /usr/include/sys/*.h
这不一定有效,因为 include file 还可能 include 其他位置的 files。更好的方法是写一个 include time.h 的 main.c,然后让 compiler 只运行 preprocessor:
prompt> gcc -E main.c
输出会包含处理完 directives 后的 structures、prototypes 和 timeval definition。
或许更好的查找方式是 Google。对于不知道的事情,应该主动搜索;只要查一查,就能学到惊人的多的东西。
Info Pages
info pages 为许多 GNU tools 提供比 man pages 更详细的 documentation。可以运行 info,或通过 emacs 执行 Meta-x info。gcc 有数百个 flags,gmake 有许多 build features,gdb 也是 sophisticated debugger。阅读 man/info pages,尝试尚未用过的 features,成为 programming tools 的 power user。
F.9 推荐阅读
很多信息可以免费在线获得,不过有时书本形式更容易学习。对于感兴趣的 topic,也可以留意 O’Reilly books,它们的质量几乎总是很高。
- The C Programming Language,Brian Kernighan 与 Dennis Ritchie 著:definitive C book。
- Managing Projects with make,Andrew Oram 与 Steve Talbott 著:合理且简短的 make 读物。
- Debugging with GDB: The GNU Source-Level Debugger,Richard M. Stallman 与 Roland H. Pesch 著:介绍 GDB 的小书。
- Advanced Programming in the UNIX Environment,W. Richard Stevens 与 Steve Rago 著:UNIX hackers 必读,也有 TCP/IP 和 Sockets programming 方面的优秀作品。
- Expert C Programming,Peter Van der Linden 著:关于 compilers 等内容的许多 useful tips 都直接借鉴于此;很有启发性,尽管有些过时。
原文逐段复核补充
本篇按官方 Version 1.10 的 13 页 lab-tutorial.pdf 逐段核对,覆盖 F.1–F.9:simple C program、gcc compilation pipeline、useful flags、library linking、separate compilation、Makefiles、gdb debugging、man/info documentation 与 suggested readings。原文没有独立 raster image;F.2 的 compilation pipeline、F.6 的 Makefile 和 F.7/F.8 的 terminal transcript 在对应正文位置分别保留为 Mermaid、代码块和 text code block。PDF 页眉、页脚、页码和版本标识不作为正文内容录入。
官方示例中的 /usr/include、/usr/lib、libm.a、libm.so、gdb transcript、open() return values、errno、gettimeofday() 与 gcc -E main.c 均逐项保留;本机 build/run evidence 单独放在“实验执行记录”,不把源文档示例误报为本机实验结果。
关键结论
- C systems programming 不只是 language syntax,还需要掌握 compiler、linker、debugger、build tool 和 documentation。
gcc是 compiler driver,协调 preprocessor、compiler、assembler 和 linker。- static/dynamic linking、
-I/-L和 library search path 是从 source 到 executable 的关键连接点。 - separate compilation 与
make能减少大型项目的重复工作;timestamp 和 dependency 决定哪些 target 需要重建。 gdb通过 breakpoint、stepping、variable inspection 和 core/attach 能力,把 crash 转成可分析的 program-state evidence。- man/info pages 还应查 header、arguments、return values、
errno和 error semantics。
实验执行记录
| 检查项 | 状态 | 记录 |
|---|---|---|
| compiler/toolchain 版本 | ✅ 已记录基线 | Apple clang 21.0.0(gcc driver)、GNU Make 3.81;macOS workspace |
| 最小 C 程序 | ✅ 已执行 | ostep-code HEAD ba628e3dd929389dcd78c933d330dd5e70ddca85;intro 目录 make 成功编译 cpu、mem、threads、io |
| separate compilation/Makefile | ✅ 已执行 | cpu-api、threads-api、vm-intro 目录 make 成功;threads-api 使用 -Wall -Werror -pthread |
| gdb debugging | ⏸ 环境限制 | 当前 macOS 环境未安装 gdb;已尝试 lldb,breakpoint 可创建,但运行时被系统拒绝 attach(attach failed (Not allowed to attach to process)) |
| man/info 查阅 | 🔄 部分完成 | man -w 2 open 与 man -w 1 kill 成功定位文档;当前环境未安装 GNU info |
本表是实验性完成的唯一入口。仅有教程文字或命令示例时,不将状态标记为已验证。
已执行命令与结果
git clone https://github.com/remzi-arpacidusseau/ostep-code.git
git -C ostep-code rev-parse HEAD
ba628e3dd929389dcd78c933d330dd5e70ddca85
cd ostep-code/intro && make
gcc -o cpu cpu.c -Wall
gcc -o mem mem.c -Wall
gcc -o threads threads.c -Wall -pthread
gcc -o io io.c -Wall
cd ../cpu-api && make
cd ../threads-api && make
cd ../vm-intro && make
以上是 build evidence,不代表所有 project tests 或 xv6 emulator 已通过。
环境限制记录
Apple clang version 21.0.0 (clang-2100.3.34.2)
GNU Make 3.81
gdb: not installed
info: not installed
man -w 2 open -> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/share/man/man2/open.2
man -w 1 kill -> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/share/man/man1/kill.1
intro/cpu 与 intro/mem 是刻意的无限循环示例,不能直接作为普通 smoke test;曾因直接运行而超时,已终止对应临时进程。intro/threads 2 成功输出 Initial value : 0 / Final value : 4,intro/io 成功写入并 fsync /tmp/file,内容为 hello world\n。这些是示例级运行证据,不代表完整 project tests 通过。
与已有笔记的关系
- OSTEP:Process API:system call wrapper 与 UNIX interface。
- OSTEP:Memory API:C pointer、allocation 与 segmentation fault。
- OSTEP:Thread API:后续 systems projects 会使用 POSIX threads。
- OSTEP:附录与实验材料索引:实验材料总入口。
- 下一篇:OSTEP:Laboratory:Systems Projects。
参考资料
评论 (0)