How do Compilers work?
Hello everyone hope you all are pink in health. In this blog, I am going to write, how compilers work. We all know the importance of compilers. Without them, it is really difficult for us to see the output of our code. We will be highly satisfied with our output and don't bother how we landed up there. Here is the answer, what actually happens inside.
Generally, programming languages were created to allow developers to write human-readable source code. However, computers work with machine code, which people can hardly write or read. Thus, compilers translate the programming language's source code to machine code dedicated to a specific machine.
The compilation process consists of several phases. They are:
- Lexical analysis
- Syntax analysis
- Semantic analysis
- Intermediate code generation
- Code generation.
Now let's see what they mean exactly.
The first stage of the compilation process is lexical analysis. During this phase, the compiler splits source code into fragments called lexemes. A lexeme is an abstract unit of a specific language's lexical system.
In this phase, the compiler checks the grammatic structure of the source code and its syntax correctness.
Syntax analysis is responsible for two tasks:
- It checks source code for any syntax error.
- it generates an abstract syntax tree that the next stage uses.
In this stage, the compiler uses an abstract syntax tree to detect any semantic errors, for example:
- Assigning the wrong type to a variable
- Declaring variables with the same name in the same scope.
- Using an undeclared variable
- Using languages keyword as a variable name
Intermediate Code Generation:
During this compilation process, a compiler can generate one or more intermediate code forms.
Intermediate code is machine-independent. Thus, there is no need for unique compilers for every different machine. Besides, optimization techniques are easier to apply to intermediate code than machine code.
In the optimization phase, the compiler uses a variety of ways to enhance the efficiency of the code.
Finally, the compiler converts the optimized intermediate code to the machine code dedicated to the target machine. The final code should have the same meaning as source code and be efficient in terms of memory and CPU resource usage. Furthermore, the code generation process must also be efficient.
GNU Compiler Collection:
GCC consists of compilers for several programming languages. They are:
- C (gcc)
- C++ (g++)
- Objective-C (gobjc)
- Fortran (g77 and GFortran)
- Java (gcj)
- Ada (gnat)
Connect With Me