参考 the-swift-compiler-for-beginners
编译Swift源文件
创立main.swift
, 输入如下代码
print("Hello world!")
# 编译 main.swift, -o 设置生成的可履行程序姓名
swiftc main.swift -o hello
# 履行hello可履行程序,输出"Hello world!"
./hello
-D
设置条件编译标志
为true
#if(DEBUG)
print("debug mode")
#endif
print("Hello world!")
# 设置条件编译DEBUG并履行程序
swiftc main.swift -D DEBUG && ./main
编译多个Swift文件
# point.swift
struct Point {
let x: Int
let y: Int
}
# main.swift
#if(DEBUG)
print("debug mode")
#endif
let p = Point(x: 4, y: 20)
print("Hello world!", p.x, p.y)
swiftc point.swift main.swift -o point-app
# 输出Hello world! 4 20
./point-app
-v
增加 -v(verbose) 参数输出 swiftc 具体履行进程
swiftc point.swift main.swift -o point-app -v

- usr/bin/swift 别离编译 main.swift point.swift
- usr/bin/ld
链接
两个目标文件.o
, 生成可履行程序point-app
编译 – 前后端分离

不同的编译器前端
, 方便扩展新言语
- C -> Clang/GCC
- Objective-C -> Clang
- Swift -> swiftc
- others….
生成一致的 LLVM IR文件
交给一致的编译器后端
LLVM 编译成各个架构的可履行程序, 如ARM x86等
编译具体进程

- 语法分析生成
笼统语法树(AST)
swiftc -dump-ast main.swift

- 生成
中心层代码(SIL)
swiftc -emit-sil main.swift

- llvm中心表示层(IR)
swiftc -emit-ir main.swift

- 生成汇编代码
swiftc -emit-assembly main.swift

swiftc main.swift -o main.o
swiftc point.swift -o point.o
- 链接生成可履行程序
ld main.o point.o -o main
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。