A compiler is a program that translates source code written in one language into another language, usually lower-level machine code, bytecode or an intermediate representation, before the program runs. In programming fundamentals it is the counterpart of the interpreter: the compiler does its translation ahead of execution, so the resulting program can run without the translator present.
Beyond translation, a compiler detects errors early and optimizes the generated code. Type errors, undeclared variables and syntax mistakes are reported at build time rather than in front of users, and the output is usually far faster than a naive line-by-line execution of the same source.
How a compiler translates source code
A compiler works as a pipeline of phases, each transforming the program into a representation that is easier for the next phase to process. The phases are commonly grouped into a front end that understands the source language, a middle end that optimizes, and a back end that targets a specific processor.
The table below lists the classic phases and what each one produces.
| Phase | Input | Output | Main task |
|---|---|---|---|
| Lexical analysis | Characters | Tokens | Group characters into keywords, names, literals |
| Parsing | Tokens | Syntax tree | Check grammar and build structure |
| Semantic analysis | Syntax tree | Annotated tree | Resolve names, check types and scope |
| IR generation | Annotated tree | Intermediate code | Lower to a machine-neutral form |
| Optimization | Intermediate code | Improved IR | Remove waste, simplify computation |
| Code generation | Improved IR | Assembly or object code | Select instructions, allocate registers |
The intermediate representation (IR) is the key design decision. A well-designed IR, often in static single assignment form, lets one optimizer serve many source languages and many target processors. This is why toolchains such as LLVM and GCC support several languages with a shared core.
Compilation usually ends with object files, not a finished program. A separate linker combines object files and libraries, resolves references between them and writes the final executable or shared library.
Kinds of compilers
Compilers differ by when they run and what they produce. The same language can be served by several kinds, and many modern runtimes combine more than one.
| Compiler type | When it runs | Output | Typical languages |
|---|---|---|---|
| Ahead-of-time (AOT) | Before distribution | Native machine code | C, C++, Rust, Go |
| Bytecode compiler | Before or at load time | Virtual machine bytecode | Java, C#, Python |
| Just-in-time (JIT) | During execution | Native code for hot paths | JavaScript engines, JVM, .NET |
| Cross-compiler | On a different host | Code for another platform | Embedded firmware, mobile |
| Transpiler | Before execution | Source in another language | TypeScript to JavaScript |
A just-in-time compiler profiles the running program and compiles the most frequently executed code with optimizations informed by real data. It trades startup time and memory for strong long-run performance, which makes it attractive for servers and browsers.
Compiler versus interpreter
The difference between a compiler and an interpreter is when translation happens, not which language is used. Languages are not inherently compiled or interpreted; implementations are. Many runtimes first compile to bytecode and then interpret or JIT-compile it.
| Aspect | Compiler | Interpreter |
|---|---|---|
| Translation time | Before execution | During execution |
| Startup speed | Fast, code is ready | Fast, no build step |
| Execution speed | Usually high | Usually lower |
| Error detection | Many errors at build time | Errors appear when code runs |
| Distribution | Platform-specific binaries | Source plus interpreter |
| Development cycle | Edit, build, run | Edit, run |
Static typing makes compilation especially valuable, because the compiler can prove the absence of whole classes of errors and choose efficient machine representations for each data type. In dynamically typed languages, much of this checking must wait until run time.
Optimizations and diagnostics
An optimizing compiler rewrites the program to run faster or use less memory while preserving its observable behavior. Optimization levels such as -O0, -O2 and -O3 in common C and C++ compilers control how aggressively it does so.
- Constant folding evaluates expressions like
60 * 60at compile time. - Dead code elimination removes code whose result is never used.
- Function inlining replaces a call with the function body to avoid call overhead.
- Loop optimizations hoist invariant work out of loops and enable vectorization.
- Register allocation keeps frequently used values in processor registers.
Compilers also produce diagnostics: errors stop the build, while warnings flag suspicious but legal code such as unused variables or implicit narrowing conversions. Treating warnings as errors in continuous integration is a widely used quality practice.
Common problems and misconceptions
Many compiler-related problems arise from assumptions the language does not guarantee. In C and C++, undefined behavior such as signed integer overflow allows the optimizer to assume it never happens, so code that seemed to work at -O0 may change behavior at higher optimization levels.
| Symptom | Likely cause | Remedy |
|---|---|---|
| Works in debug, fails in release | Undefined behavior exposed by optimization | Use sanitizers, fix the code |
| Undefined reference at build end | Missing library in the linker step | Add the library to link options |
| Slow build times | Large headers, full rebuilds | Incremental builds, precompiled headers |
| Binary runs only on build machine | Wrong target or dynamic dependencies | Set the target, bundle libraries |
| Debugger shows wrong lines | Optimized code without full debug info | Build with debug symbols, lower optimization |
A frequent misconception is that compiled code is always faster. A good JIT can match or exceed AOT output for some workloads, and algorithm choice usually matters far more than the translation strategy.
Another misconception is that a compiler guarantees correct programs. It verifies syntax, types and declared rules, but it cannot know the intended logic, so testing, code review and runtime error handling remain necessary even when the build finishes without a single warning.
Explained without jargon
Computers only understand very simple numeric instructions, while people write programs in languages that look closer to English and mathematics. A compiler is the translator between the two.
Imagine translating a whole book before anyone reads it, instead of translating aloud sentence by sentence. The translation takes time at first, but afterwards readers get the finished version instantly, and the translator can fix awkward passages and spot mistakes before the book is printed.
A typical use case
A small team builds firmware for an industrial temperature sensor with an ARM microcontroller, 256 KB of flash memory and 32 KB of RAM. Developers write the code in C on ordinary laptops and use a cross-compiler that produces machine code for the ARM target instead of for the laptop processor.
During development they compile with -O0 and debug symbols so each source line maps cleanly to the debugger. For release they switch to size optimization with `-Os`, enable all warnings as errors and run the build in continuous integration. The optimizer removes unused library functions and inlines small helpers, shrinking the image from about 210 KB to 140 KB, which leaves room for a secure firmware update feature without changing the hardware.