🧠 What is a Compiler?
A Compiler is a special program that translates source code written in a high-level programming language (like C, C++, Java) into machine code (binary) that a computer’s CPU can understand and execute.
It’s like translating human instructions into a language only the CPU can speak.
🛠️ Why Do We Need a Compiler?
-
CPUs only understand machine code (1s and 0s).
-
We humans write code in high-level languages.
-
A compiler bridges that gap by translating our code into a low-level executable file (like
.exe,.out, or.class).
📦 Compiler Workflow: The 6 Main Stages
| Phase | What It Does |
|---|---|
| 1. Lexical Analysis | Breaks code into tokens (like words in a sentence) |
| 2. Syntax Analysis | Checks grammar using parsing (builds syntax tree) |
| 3. Semantic Analysis | Checks for meaning (e.g., variable types, scope) |
| 4. Intermediate Code Generation | Converts code into an intermediate representation (IR) |
| 5. Optimization | Improves the IR for performance or size |
| 6. Code Generation | Converts IR into machine code (CPU instructions) |
This entire process happens when you compile a
.cor.cppfile usinggccorg++.
⚙️ Output of a Compiler
| Language | Output |
|---|---|
| C, C++ | Executable binary (.exe, .out) |
| Java | Bytecode (.class) – run by JVM |
| TypeScript | JavaScript – run by browser |
🎯 Types of Compilers
| Type | Description |
|---|---|
| Single-pass | Translates in one go, fast but less optimized |
| Multi-pass | More accurate and optimized, but slower |
| Cross compiler | Compiles code on one machine for a different platform/CPU |
| Just-In-Time (JIT) | Used in Java/Python – compiles at runtime for performance |
🧪 Real-World Examples:
| Compiler | Language |
|---|---|
gcc | C |
g++ | C++ |
javac | Java |
tsc | TypeScript |
rustc | Rust |
🧠 Interview-Ready Definition:
A compiler is a software tool that translates code written in a high-level language into machine code that can be executed by the computer’s CPU. It performs lexical, syntactic, semantic analysis, optimization, and code generation to produce an executable file.
✅ Bonus: Compiler vs Interpreter (Quick Peek)
| Feature | Compiler | Interpreter |
|---|---|---|
| Output | Full machine code | Executes line-by-line |
| Speed | Faster (after compilation) | Slower |
| Example | C | Python, JavaScript |
| Execution | Prepares once, runs many times | Interprets every time |