What is compiler and How it works? Its compiler that makes our high level language understandable to computer, by translating it into machine code or low level language. This means compiler is a Translator. In simple words we can define compiler as a system program that translates code written in high-level language like c, c++ into an equivalent low level language like machine language.
How compiler works ?
Here is the animated video which will make you clear, how compiler works in translating the high level language into machine language.
During the translation of high level language to machine code, compiler goes through some phases. Compilation is carried out in two parts : Analysis and Synthesis.
Analysis is carried out in three phases by compiler :
1. Lexical Analysis
2. Syntax Analysis
3. Semantic Analysis
and Synthesis Analysis is carried out in this phases :
4. Intermediate Code Generation
5. Code Optimization
6. Code Generation.
The figure shows below will show, the flow graph for the phases to occur .
Task performed by Compiler during their respective phases :
1. LEXICAL ANALYSIS : This phase is also called as scanning. In this phase a complete source program is scanned and is broken up into groups of strings called token.
Tokens for a language can be identifiers, constants, relational operators, keywords.
2. SYNTAX ANALYSIS :This phase is also called as parsing. In this phase tokens are grouped together to form a hierarchical structure called as parse tree or syntax
tree. It determines the structure of a source string by grouping the tokens.
3. SEMANTICS ANALYSIS : This phase determines the meaning of the source string i.e checks for matching of parenthesis in the expression, or matching of if..else statement, or performing arithmetic operations of the expressions or checking the scope of operation.
4. INTERMEDIATE CODE GENERATION : This phase generates an intermediate code which can be in the forms of three address code, quadruple, triple, posix.
5. CODE OPTIMIZATION :This phase attempts to improve the intermediate code by making its execution faster and to lessen the consumption of memory. Hence the overall
running time of the target program can be improved.
6. CODE GENERATION :In this phase the target code is generated i.e the intermediate instructions are translated into sequence of machine instructions.
I hope you enjoyed this article reading and might made some basic concept for compiler working. If you like to add more on this, do comment below.e