编译技术1-4
编译技术1-4
Language Processing Systems 语言处理系统
1. What is a Compiler? 什么是编译器?
Definition 定义 A compiler is a computer program that
translates source code (high-level language) into target code
(machine/assembly language).
编译器是将源代码(高级语言)转换为目标代码(机器/汇编语言)的计算机程序。
Input/Output 输入输出 | | Compiler 编译器 | |--|----------------| | Input (输入) | High-level language (e.g., C, C++, Java) 高级语言(如C/C++/Java) | | Output (输出) | Machine code or assembly 机器码或汇编语言 |
Process Flow 流程
1 | Source Program (源代码) → Compiler (编译器) → Target Program (目标程序) |
先把源程序通过编译器变成目标程序!
接着输入通过目标程序生成输出!
2. Interpreter vs. Compiler 解释器 vs. 编译器 Similarities 共同点 Both are language implementation systems (均属于语言实现系统).
Differences 区别 | Feature 特性 | Interpreter 解释器 | Compiler 编译器 | |-------------|----------------------|-------------------| | Execution 执行方式 | Directly executes source code 直接执行源代码 | Generates standalone executable 生成可独立执行的目标代码 | | Speed 速度 | Slower (逐行解释) | Faster (预编译优化) | | Optimization 优化 | Minimal or none 基本无优化 | Extensive optimizations 深度优化 | | Examples 例子 | Python, JavaScript | GCC, Clang |
Key Insight 核心结论 • Interpreters run programs "as is" (解释器直接运行原始代码).
• Compilers preprocess thoroughly (编译器会深度预处理).
解释器则时将源程序和输入一起放进解释器然后生成输出!
3. Hybrid Approach: Just-In-Time (JIT) 混合方法:即时编译 JIT Compilation (即时编译) • Combines interpretation + compilation (解释与编译结合).
• Used in Java/.NET (Java和.NET的实现方式).
Java Workflow (Java工作流)
1 | Java Source Code (.java) → Java Compiler → Bytecode (.class) → JVM (Interpreter/JIT) → Execution |
Compilation Phase 编译阶段
•.java
→.class
(Platform-independent bytecode 平台无关字节码).Runtime Phase 运行时阶段
• JVM interprets bytecode or JIT-compiles to machine code.• JVM根据情况选择解释执行或即时编译为机器码.
4. Mixed Compiler Systems 混合编译器系统
Workflow 流程
1 | Source Language → Compiler → Intermediate Code → Virtual Machine → Output |
• Intermediate Code (中间代码)
• 跨平台的中间表示(如Java字节码、LLVM IR).
• Virtual Machine (虚拟机)
• 执行中间代码(解释/JIT编译).
Examples 应用案例
• Java: .java
→ javac
→ .class
→
JVM
• Python: Source → Python VM bytecode → Interpreter
5. Comparative Summary 对比总结
Aspect 方面 | Compiler 编译器 | Interpreter 解释器 | Hybrid (JIT) 混合系统 |
---|---|---|---|
Output 输出 | Machine code 机器码 | None (直接执行) | On-demand machine code 按需生成机器码 |
Startup Speed 启动速度 | Slow (需完整编译) | Fast | Moderate (混合延迟) |
Long-term Performance 长期性能 | Best (充分优化) | Poor | Good (热点代码优化) |
Use Cases 用例 | C/C++, Go | Python, Ruby | Java, C# |
6. Key Takeaways 核心要点 1. Compilers enable
efficiency (编译器实现高效执行).
• 通过预处理和优化生成高质量目标代码.
Interpreters prioritize flexibility (解释器侧重灵活性).
• 无需编译,跨平台直接运行.Modern systems use hybrids (现代系统采用混合策略).
• JIT编译平衡了启动速度和运行性能.
"Compilers translate human intent; interpreters execute it
immediately."
"编译器翻译人类意图,解释器立即执行。"