🧠 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

PhaseWhat It Does
1. Lexical AnalysisBreaks code into tokens (like words in a sentence)
2. Syntax AnalysisChecks grammar using parsing (builds syntax tree)
3. Semantic AnalysisChecks for meaning (e.g., variable types, scope)
4. Intermediate Code GenerationConverts code into an intermediate representation (IR)
5. OptimizationImproves the IR for performance or size
6. Code GenerationConverts IR into machine code (CPU instructions)

This entire process happens when you compile a .c or .cpp file using gcc or g++.


⚙️ Output of a Compiler

LanguageOutput
C, C++Executable binary (.exe, .out)
JavaBytecode (.class) – run by JVM
TypeScriptJavaScript – run by browser

🎯 Types of Compilers

TypeDescription
Single-passTranslates in one go, fast but less optimized
Multi-passMore accurate and optimized, but slower
Cross compilerCompiles 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:

CompilerLanguage
gccC
g++C++
javacJava
tscTypeScript
rustcRust

🧠 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)

FeatureCompilerInterpreter
OutputFull machine codeExecutes line-by-line
SpeedFaster (after compilation)Slower
ExampleCPython, JavaScript
ExecutionPrepares once, runs many timesInterprets every time