Compilation
Table of Contents
1. Execution Steps
“Compiling” a program involves four steps: the compiler, assembler, linker, and loader (CALL):
The compiler translates code to assembly language. The assembler converts the assembly to binary. The linker allows separate compilation of files (e.g. changes to one file does not require recompilation of the entire program): here, multiple binary files from the assembler are “linked” to create the final executable, which the loader loads into memory to be run.
2. Compiler
The compiler handles several steps, translating code to assembly:
- Preprocessing: Handles all preprocessr commands and macros.
- Lexical analysis: Splits code into tokens that can be given individual semantic meaning.
- Semantic analysis: Parse the sentence structures using the tokens so that the meaning can be determined. Often uses a syntax tree to acquire context.
- Optimization: Optional, attempt to rewrite input code to be more efficient.
- Encoding: Generate the code in assembly.
3. Assembler
The assembler converts assembly code into binary. It is responsible for converting pseudoinstructions with true assembly instructions. It produces an object file that contains both this module’s instructions and information for downstream steps (e.g. linking and debugging).
The assembler performs two passes over the program to compute all offsets. The first pass stores the positions of labels in a symbol table, and then the second pass uses these positions to generate the offsets in machine code. Any references that it cannot handle (e.g. other files, static data) is stored in a relocation table. The assembler defers to the linker any references that depend on knowing other object modules.
4. Linker
The linker links multiple assembly files by putting together the text segments and data segments. It also resolves references in the relocation table by filling in absolute addresses for external labels and static data. This method is known as static linking.
5. Loader
The loader loads a program into a newly created address space. It reads the a.out file header for sizes of text and data segments, and creates a new address space for the program large enough to hold its text and data segments, along with a stack segments