How a computer language compiler works

The programs that are written in languages like C++ or C are just text. Computers don't understand that text as it is. The program (the text) has to be compiled (translated into another language) into machine language which is the actual language that the CPU understands.

Why ? you ask. Well it's because development in pure machine language is slow and prone to errors. And machine language doesn't look like our spoken language which makes it hard to learn and understand.And because it takes a long time to learn machine language. And because people after a long time programming in machine language have observed some patterns emerging and they gave those patterns names like : for loops, do while loops, while loops, if decisional blocks, functions etc.

Like spoken languages, computer programming languages have an alphabet(lexicum) of words that mean(do) something. So the first thing that a compiler does is to analyze the words of a program, that's lexical analysis.

After the compiler checks using lexical analysis that the words used are the ones from the language it does does a syntax analysis. Syntax analysis checks if the combination of words used follow a predetermined grammar.

After syntax analysis comes semantical analysis in which the compiler checks if the meaning of the expressions made from the language's words make sense.

After that the compiler starts replacing expressions in the high programming language with expressions in assembly language. Before this step there can be a step of intermediate representation and intermediate optimization.

Here's a picture from a book called the "Dragon Book", a book about compilers.
This picture gives a good example how an expression in a high language is transformed(translated) into an expression in machine language :

how a compiler works

No comments :

Post a Comment