Compiler

On this page 7

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.

PhaseInputOutputMain task
Lexical analysisCharactersTokensGroup characters into keywords, names, literals
ParsingTokensSyntax treeCheck grammar and build structure
Semantic analysisSyntax treeAnnotated treeResolve names, check types and scope
IR generationAnnotated treeIntermediate codeLower to a machine-neutral form
OptimizationIntermediate codeImproved IRRemove waste, simplify computation
Code generationImproved IRAssembly or object codeSelect instructions, allocate registers
Phases of a typical compiler

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 typeWhen it runsOutputTypical languages
Ahead-of-time (AOT)Before distributionNative machine codeC, C++, Rust, Go
Bytecode compilerBefore or at load timeVirtual machine bytecodeJava, C#, Python
Just-in-time (JIT)During executionNative code for hot pathsJavaScript engines, JVM, .NET
Cross-compilerOn a different hostCode for another platformEmbedded firmware, mobile
TranspilerBefore executionSource in another languageTypeScript to JavaScript
Main compiler types and their output

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.

AspectCompilerInterpreter
Translation timeBefore executionDuring execution
Startup speedFast, code is readyFast, no build step
Execution speedUsually highUsually lower
Error detectionMany errors at build timeErrors appear when code runs
DistributionPlatform-specific binariesSource plus interpreter
Development cycleEdit, build, runEdit, run
Compiled and interpreted execution compared

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 * 60 at 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.

SymptomLikely causeRemedy
Works in debug, fails in releaseUndefined behavior exposed by optimizationUse sanitizers, fix the code
Undefined reference at build endMissing library in the linker stepAdd the library to link options
Slow build timesLarge headers, full rebuildsIncremental builds, precompiled headers
Binary runs only on build machineWrong target or dynamic dependenciesSet the target, bundle libraries
Debugger shows wrong linesOptimized code without full debug infoBuild with debug symbols, lower optimization
Typical compiler problems and remedies

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.