Introduction to Compiling
M.A Doman
What is a compiler?
A compiler is a program that reads a program written in one language and translates it into another languageCompiler reports the presence of errors in the source program
compiler
SourceProgram
TargetProgram
Error Messages
Preprocessing
The first pass of the compilerReads each source fileEvery time it hits an directive #include it goes and gets the header file named. It then reads and processes it.Expands macrosPasses the results to the next phase of the compiler.
Preprocessing
Macro preprocessingAllows the user to define macros that are shorthand for larger constructsDefine variables/identifiers#define _card.h#define BUFFER_SIZE 256Conditional expressions#if .. #elseContain parameters#define max(a,b)(a>b ? a: b)
Card.h
Card.cpp
main.cpp
Preprocessor
Compilation Model
AnalysisBreaks up the source into pieces and constructs and creates an intermediate representation of the source programSynthesisConstructs the desired target from the intermediate representation
2-6
Compilation Analysis
Linear or lexical analysisThe source is read as a stream of characters and grouped intotokensposition = initial + rate * 60;Tokens:position : Identifier of type double= : assignment operatorinitial : identifier of typedouble+ : plus operatorrate : Identifier of type double* : multiplication operator60 : constant of 60 (int)
8-7
Compilation Analysis
Hierarchal / Syntax analysisAlso called parsingGroups the tokens into grammatical phrases that the compiler will later use to synthesize the logic.Usually represented by a parse tree:
8-8
Compilation Analysis
Example (broad) of a parse tree:position = initial + rate * 60;
8-9
Operator=
Identifier
position
Operator+
Identifier
initial
Operator*
Identifier
rate
integer
60
Identifiers are oftypedouble60is an constantinteger.
Compilation Analysis
Semantic AnalysisChecks the source program for semantic errorsGathers type informationDoes type checking
Operator*
Identifier
rate
integer
60
Linking
The result of the analysis phase of compilation is an file of type ‘o’.Example pgm.cpp –compiler->pgm.oOnceall the object (.o) files are created, they are passed to thelinkerAll references are resolvedFinished product: an executableprogramExamplepgm.o–linker__->pgmora.out
Stack.o
Library functions
StackTest.o
Linker
Node.o
a.out
Card.h
Card.cpp
main.cpp
Compiler
Preprocessor
Card.o
Libraryfunctions
Linker
main.o
a.out
0
Embed
Upload