[swarthmore cs75] inlab1 — Tiny Compiler
课程回顾
Swarthmore学院16年开的编译系统课,总共10次大作业。本随笔记录了inlab1的实践过程。
tiny compiler
这个迷你的编译器可以将一个源文件,编译成可执行的二进制代码。它包括以下文件:
87.int:源代码只包括一个整数
87
compiler.ml:将.int的源文件编译为.s的汇编文件
open Printf
let compile (program: int) : string =
sprintf "
section .text
global our_code_starts_here
our_code_starts_here:
mov eax, %d
ret\n" program;;
let () =
let input_file = (open_in (Sys.argv.(1))) in
let input_program = int_of_string (input_line input_file) in
let program = (compile input_program) in
printf "%s" program;;
命令行执行:
⤇ ocaml compiler.ml 87.int > 87.s
main.c:执行汇编代码并打印到控制台。
#include <stdio.h>
extern int our_code_starts_here() asm("our_code_starts_here");
int main(int argc, char** argv)
{
int result = our_code_starts_here();
printf("%d\n", result);
return 0;
}
命令行执行:
⤇ nasm -f macho -o 87.o 87.s
⤇ clang -m32 -o 87.run main.c 87.o
Makefile:将编译过程写成make文件
%.run: %.o
clang -m32 -o $@ main.c $<
%.o: %.s
nasm -f macho -o $@ $<
%.s: %.int
ocaml compiler.ml $< > $@
命令行执行:
⤇ make 87.run
\⤇ ./87.run
87
可能会出现的错误:
- The macOS 10.14 SDK no longer contains support for compiling 32-bit applications. If developers need to compile for i386, Xcode 9.4 or earlier is required. (39858111)
⤇ clang -g -m32 -o our_code main.c our_code.o
ld: warning: ignoring file /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/lib/libSystem.tbd, missing required architecture i386 in file /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/lib/libSystem.tbd
Undefined symbols for architecture i386:
"_printf", referenced from:
_main in main-246508.o
ld: symbol(s) not found for architecture i386
安装 Xcode 9.4.1 ,然后执行:
⤇ sudo xcode-select -s /Applications/Xcode\ 9.4.1.app
验证目前使用的clang:
⤇ xcodebuild -find clang
/Applications/Xcode 9.4.1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
- 找不到'stdio.h'头文件
⤇ clang -g -m32 -o our_code main.c our_code.o
main.c:1:10: fatal error: 'stdio.h' file not found
#include <stdio.h>
^~~~~~~~~
1 error generated.
安装headers文件:
⤇ cd /Library/Developer/CommandLineTools/Packages
⤇ open macOS_SDK_headers_for_macOS_10.14.pkg