How Programs Are Translated and Run

MODULE 3 • LESSON 02

When you press Build and run in Code::Blocks, a few seconds pass and your program appears in a console window. A great deal happens in those seconds. The processor can only execute machine code, sequences of binary instructions like the ones you met in Module 1, but you wrote your program in C, a high-level language made of words and symbols. Something has to translate one into the other.

This lesson follows one small C program all the way from the text you type to the instructions the CPU runs. You will meet the different kinds of translator (assemblers, compilers and interpreters), see how virtual machines fit in, step through every stage of compilation with real output from the gcc compiler, and learn which stage catches which kind of error.

What you will learn

  • Why high-level programs must be translated, and the meaning of source code, object code and executable code.
  • What assemblers, compilers and interpreters do, and how compilers and interpreters differ.
  • How virtual machines and bytecode let one compiled program run on many kinds of computer.
  • The stages of compilation: lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimisation and code generation.
  • The roles of the preprocessor, the linker and the loader in getting a C program to run.
  • Which stage reports which kind of error, using real gcc messages.

Part 1: Why translation is needed

A processor understands only its own machine code: binary instructions made of an opcode and operands (Module 1). Writing directly in machine code is slow and error-prone, so programmers use languages that are easier for people:

LevelExampleTranslated by
Machine code (low level)10111110 00100010 …Nothing: the CPU runs it directly
Assembly language (low level)mov $34, %esiAn assembler
High-level languagefee = hours * 6 + 10;A compiler or an interpreter

Three terms appear in every answer about translation. Source code is the program written by the programmer (fee.c). Object code is the machine-code output of a translator, which may still need to be joined with other code (fee.o). An executable is a complete machine-code program that the operating system can load and run (fee.exe).

Part 2: Assemblers, compilers and interpreters

An assembler translates assembly language into machine code. Each assembly instruction (a mnemonic such as MOV or ADD) usually becomes exactly one machine instruction, so assembling is mostly a one-to-one look-up, plus working out the addresses of labels.

A compiler translates the whole high-level program into object code before it runs. Translation happens once; after that the executable can be run as often as you like without the compiler, and it runs quickly. C is a compiled language.

An interpreter translates and executes the program one statement at a time, every time the program runs. No separate executable file is produced. Python and JavaScript are usually interpreted (strictly, they are first turned into bytecode, as you will see in Part 3).

Point of comparisonCompilerInterpreter
When translation happensThe whole program, before it runsEach statement, while the program runs
OutputAn object or executable file is producedNo executable is kept
Running the program againRun the executable; the compiler is not neededThe interpreter is needed every time
Speed of executionFast: already in machine codeSlower: translating as it goes
Error reportingReports errors for the whole program after translation; nothing runs until they are fixedStops at the first error it reaches; the statements before it have already run
DevelopmentSlower edit-compile-run cycleQuick to test small changes
Distributing the programThe executable can be shared without the source codeThe source code (or bytecode) must be shared

In an exam, “explain three differences” means three rows of this table, each written as a direct contrast: “a compiler translates the whole program before it is executed, whereas an interpreter translates and executes one line at a time.”

Part 3: Virtual machines and bytecode

Machine code is specific to one family of processors: a program compiled for an Intel laptop will not run on the ARM chip in a phone. A virtual machine (VM) solves this. It is a program that imitates a computer in software, with its own simple instruction set called bytecode.

  • Java source is compiled once into bytecode (a .class file).
  • Any device with a Java Virtual Machine (JVM) can then run that bytecode. The JVM interprets it, or uses a just-in-time (JIT) compiler to turn frequently used parts into native machine code while the program runs.
  • Python works similarly: the source is compiled to bytecode, which the Python virtual machine runs.

So a virtual machine combines both ideas: compile once to an intermediate form, then interpret (or JIT-compile) on each machine. The slogan for Java was “write once, run anywhere”. The cost is that a VM must be installed, and programs usually start more slowly than native C programs.

Part 4: From fee.c to a running program

Here is the program we will follow. It uses a preprocessor constant, a comment, a calculation and a library function:

#include <stdio.h>
#define RATE 6

int main(void)
{
    int hours = 4;
    int fee;

    /* work out the fee */
    fee = hours * RATE + 10;
    printf("Fee: $%d\n", fee);
    return 0;
}

Output:

Fee: $34

Code::Blocks hides the steps behind one button, but you can run them separately with gcc from a command prompt, and stop after any of them:

CommandWhat it does
gcc -E fee.cPreprocess only, and show the result
gcc -S fee.cCompile as far as assembly language: fee.s
gcc -c fee.cAlso assemble, giving object code: fee.o
gcc fee.o -o feeLink fee.o with the library into an executable
./feeLoad the executable and run it

The full journey has three groups of steps. The preprocessor prepares the source. The compiler analyses it and generates code, in six stages: three analysis stages that understand the program and check it for errors, and three synthesis stages that build the new code. Then the assembler, linker and loader turn that code into a running program.

Try it 1Translation stepper: follow fee.c

Tap Next to send the program through each stage. The box shows what the program looks like after that stage. The output at each stage is based on real gcc output for this program.

Part 5: The stages in detail

The preprocessor

Before compiling begins, the preprocessor carries out every line that starts with #. #include <stdio.h> pastes in the contents of the header file, which declares library functions such as printf and scanf. #define RATE 6 replaces every RATE with 6. Comments are removed. The result is still C, just longer and without any # lines.

1. Lexical analysis

The lexical analyser (scanner) reads the source one character at a time and groups the characters into tokens: keywords (int, return), identifiers (fee, hours), constants (6, 10, "Fee: $%d\n"), operators (=, *, +) and punctuators (; { }). White space and comments are discarded, and every identifier is recorded in the symbol table, which later stages use to store each name’s type and location. A character sequence that cannot form any valid token, such as a stray @ or an identifier starting with a digit, is a lexical error.

2. Syntax analysis

The syntax analyser (parser) checks that the sequence of tokens obeys the grammar of the language and builds a parse tree (syntax tree) that shows the structure of each statement, including the order of operations. Missing semicolons, unmatched brackets and missing commas between arguments are syntax errors.

3. Semantic analysis

A statement can be grammatically correct but meaningless, just as "The table ate the song" is a correct English sentence that makes no sense. Semantic analysis checks meaning: every variable is declared before it is used, operands have compatible types (type checking), functions are called with the right number of arguments, and values are converted between types where needed. An undeclared variable is a semantic error.

4. Intermediate code generation

The checked parse tree is converted into an intermediate representation: simple instructions that do not depend on any particular processor. A common form is three-address code, where each instruction has at most one operator, for example t1 = hours * 6, t2 = t1 + 10, fee = t2. Because it is machine-independent, the same front end can be used to produce code for many processors.

5. Code optimisation

The optimiser improves the intermediate code so that the final program runs faster or uses less memory, without changing its results. Examples: constant folding (working out 4 * 6 + 10 = 34 at compile time), removing dead code that can never run, and moving calculations that do not change out of loops. With gcc’s -O2 option, fee.c is optimised so far that the variables hours and fee disappear and the program simply prints 34.

6. Code generation

Finally, the code generator produces assembly language or machine code for the target processor. It chooses which registers hold which values, assigns memory locations to variables, and selects the actual instructions. The assembler then turns the assembly into an object file of machine code.

The linker and the loader

Your object file is not yet a complete program: it calls printf, but the code for printf lives in the C standard library. The linker combines your object file(s) with the library object code and the start-up code, resolves every reference between them by filling in the correct addresses, and produces a single executable. Large programs are often split into several .c files that are compiled separately and then linked. If a function is declared and called but never defined, the linker reports an undefined reference.

When you run the executable, the operating system’s loader copies it from storage into main memory, sets up the stack, and passes control to its first instruction. From then on the CPU’s fetch-decode-execute cycle takes over.

StageInputOutputErrors it can report
PreprocessorSource code with # linesExpanded source codeMissing header file
Lexical analysisCharactersTokens, symbol tableInvalid characters or tokens
Syntax analysisTokensParse treeGrammar errors: missing ; ) }
Semantic analysisParse treeChecked, annotated treeUndeclared variables, type mismatches
Intermediate codeChecked treeThree-address code–
OptimisationIntermediate codeImproved intermediate code–
Code generationOptimised codeAssembly or machine code–
LinkerObject files and librariesExecutableUndefined references
LoaderExecutable on diskProgram in memory, runningRun-time errors happen after this

Worked example: one statement through the analysis stages

Take the statement avg = total / count; where total and count are declared as int and avg as float.

  • Lexical analysis produces six tokens: identifier avg, operator =, identifier total, operator /, identifier count, punctuator ;. All three identifiers are looked up in the symbol table.
  • Syntax analysis confirms the pattern "identifier = expression ;" and builds a tree with = at the root, avg on the left and the division on the right.
  • Semantic analysis checks that all three variables are declared, sees that int / int is an int division, and notes that the int result must be converted to float before it is stored. (This is legal, but it is also why 7 / 2 stored in a float gives 3.0, not 3.5: a classic logic error you will meet in Lesson 03.)
  • Intermediate code: t1 = total / count, t2 = (float) t1, avg = t2.
  • Code generation picks an integer divide instruction followed by a conversion instruction, and stores the result in avg’s memory location.

Notice that each stage only finds the kind of problem it is designed to find. The translator cannot tell that you meant a real-number division: that is why testing is still needed after a program compiles cleanly.

Part 6: Which stage catches which error?

Knowing the stages helps you read error messages. Errors found while translating are compile-time errors (lexical, syntax, semantic) or link-time errors. Some problems are never caught by the translator: a run-time error happens while the program is running (such as dividing by zero), and a logic error means the program runs but gives the wrong answer.

Try it 2Which stage catches it?

Each piece of C has one problem. Decide which stage reports it. After you answer you will see the real message gcc gives.

Read gcc messages from the top. Fix the first error and compile again: one missing semicolon can cause a cascade of later messages that disappear once it is fixed. Always compile with warnings switched on (-Wall; in Code::Blocks, tick "Enable all common compiler warnings"), because warnings such as the one for if (x = 5) often point at logic errors.

Try it 3Translation practice

Pick a mode. "Translators" describes a job: choose the program that does it. "Compiler stages" describes a task: choose the stage.

Summary

IdeaRemember
AssemblerAssembly mnemonics to machine code, roughly one-to-one.
CompilerWhole program, before running; produces object code; fast to run.
InterpreterOne statement at a time, every run; no executable; stops at first error.
Virtual machineRuns bytecode in software, so one compiled program runs on many platforms (JVM).
Compilation stagesLexical, syntax, semantic analysis; intermediate code, optimisation, code generation.
Preprocessor, linker, loader# lines before compiling; join object code and libraries; load into memory and run.

Review questions

1. Explain THREE differences between a compiler and an interpreter.

Show answer

Any three contrasts, e.g.: a compiler translates the whole program before execution, whereas an interpreter translates and executes one statement at a time; a compiler produces an executable that can be run without the compiler, whereas an interpreter is needed each time; compiled programs run faster; a compiler reports all errors after translation, whereas an interpreter stops at the first error it meets.

2. What does an assembler do?

Show answer

It translates a program written in assembly language (mnemonics such as MOV, ADD) into machine code, usually one machine instruction per assembly instruction.

3. State the role of a linker.

Show answer

It combines the object code produced by the compiler with other object files and library code (e.g. printf) and resolves the references between them, producing a single executable program.

4. Describe what happens during lexical analysis.

Show answer

The source code is read character by character and grouped into tokens (keywords, identifiers, constants, operators, punctuators); white space and comments are removed; identifiers are entered into the symbol table; invalid tokens are reported as lexical errors.

5. Distinguish between syntax analysis and semantic analysis, giving an example error for each.

Show answer

Syntax analysis checks that the tokens follow the grammar rules and builds a parse tree (error: a missing semicolon). Semantic analysis checks that the statements make sense, such as declared variables and compatible types (error: using an undeclared variable).

6. Give TWO examples of code optimisation.

Show answer

Constant folding (replacing 4 * 6 + 10 with 34 at compile time); removing dead (unreachable) code; moving unchanging calculations out of loops.

7. Explain how a virtual machine allows a Java program to run on different types of computer.

Show answer

The Java source is compiled once into bytecode, which is not tied to any processor. Each type of computer has its own Java Virtual Machine that interprets (or JIT-compiles) the bytecode into its own machine code, so the same bytecode runs anywhere a JVM is installed.

8. A program compiles and links without errors but prints the wrong total. What kind of error is this, and which translation stage could have caught it?

Show answer

A logic error. No stage of translation can catch it, because the program is valid C; it must be found by testing, for example with trace tables or the debugger.

Homework

  1. Copy fee.c into Code::Blocks. Introduce one error at a time (a lexical error, a syntax error, a semantic error and a missing function body) and record the exact message for each in a table with the stage that reported it.
  2. If you can use a command prompt with gcc, run gcc -E fee.c and count roughly how many lines the preprocessor produced. Why is the output so much longer than your program?
  3. Write the three-address code for avg = (a + b + c) / 3;
  4. Draw a labelled diagram of the whole journey from source code to running program, naming each stage, its input and its output.
  5. Find out whether these are usually compiled, interpreted or run on a virtual machine: C, Python, Java, JavaScript, C#. Give one reason for each.

Mastery quiz: Translation

This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

Mastery quiz: How Programs Are Translated and Run

Your course badges: loading saved progress…

View badges

    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

    Saved in this browser on this device. Clearing browser data may remove your badges.

    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

    1. Which program translates a whole high-level program at once and produces a stand-alone executable?
    2. Which translator converts mnemonics such as MOV and ADD into machine code?
    3. An interpreter...
    4. The correct order of these compiler stages is...
    5. Which stage removes comments and breaks the source into tokens?
    6. A missing semicolon is reported during...
    7. Using a variable that was never declared is detected during...
    8. Which program combines object code with library code to make an executable?
    9. The Java Virtual Machine runs...
    10. Replacing 4 * 6 + 10 with 34 at compile time is an example of...

    Exam tips

    Specimen Unit 1 Paper 01 (2021), Items 39 and 41. Recognising the translator that produces a stand-alone program, and putting the main compilation stages in order. Remember the order: lexical, syntax, (semantic), then code generation.

    Specimen Unit 1 Paper 02 (2021), Question 5(b). Differences between a compiler and an interpreter. Give three separate points (when translation happens, whether an executable is produced, how errors are reported, speed), each as a contrast.

    CAPE 2024 Unit 1 Paper 02, Question 6(b). Describing individual compilation stages. For each stage say what goes in, what it does and what comes out, and name an error it detects where there is one. A worked answer is in the Go further box.

    Do not mix up the linker and the loader: the linker builds the executable file; the loader puts it into memory when you run it.

    More worked answers are on the CS Solutions page.

    Previous: Module 3 • Lesson 01 – Programming Paradigms: Imperative, Object-Oriented, Functional and Declarative. Next: Module 3 • Lesson 03 – Variables, Data Types and Assignment in C (with enum).

    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Programming (Unit 1, Module 3). Specific Objective 2: explain how assemblers, compilers, virtual machines and interpreters are involved in the execution of high-level programming languages (stages in the translation process: lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimisation, code generation; the role of preprocessors and linkers).

    Video search terms

    Search YouTube for: "compiler vs interpreter", "phases of a compiler", "lexical analysis tokens", "what does a linker do", "Java virtual machine bytecode".

    Try it 4Quick quiz

    Tap an answer. All eight questions are self-checks on this lesson.

    Updates

    2026/12/01

    - Updated the copyright line.

    2026/11/24

    - First version of the lesson.

    © 2026 islandclass.org

    Leave a Reply