What is Compiler : Understand With A Real Life Example

Syed Zubair
2 min readOct 5, 2023

Let’s understand how compiler works internally

Compilers are Translators.
Lets understand with an Example — consider a person A speaks English and person B speaks Chinese. As English language is widely used and understandable almost by every individual compare it with High level programming language and Chinese as Low level language (Byte Code).

Suppose Person A and B met for a business deal and they both can’t do communication due to language problem, Now comes a translator (person c) to help them understand by translating the languages and make them understand each other, this is what exactly our compiler does -

Here, the compiler acts as person C — It translates the Entire Source Code of a program to Machine Code in one go.

compilation of a program

The Generated Machine Code is stored in separate file which can be executed multiple times without compilation.(lets say person A (English) said some sentence “Hello”, person C (Translator) translates and make notes and give it to person B (Chinese) )
With the help of notes person B doesn’t have to ask person C to translate “Hello” again and again.

This is what exactly compiler does, compile once and run multiple times.

Technically the Job of compiler :

“Compiler is not a hardware its a piece of code (set of instructions) that compiles a program.”

  1. Translates the entire source code of program into machine code and generates an intermediate code.
  2. The Generated code stored in a separate file which can be executed multiple times.
  3. All the syntactical errors are reported all at once during compilation.
  4. Compiled codes runs faster, as its converted to machine code, that a machine can understand easily.

Example of a Compiler:
Consider a C++ program called abc.cpp. Using a C++ compiler like GCC to compile it. When a program is compiled, it checks the entire abc.cpp file for syntax errors and translates it into machine code, creating an executable file called abc.exe. Finally we can run abc.exe as many times we want without recompiling unless we make any changes to the source code.

#include <iostream>
using namespace std;

int main() {
int a = 5;
int b = 7;
int add = a + b;
cout << "The sum is: " << add ;
return 0;
}

Program is written and its ready for compilation , using a ++ compiler (GCC)

>> g++ add.cpp -o sum

The compiler analyze the entire program add.cpp file, checks it for syntax errors, and generated executable file (Machine Code) called add.

As soon as any syntactical errors are triggered the compilation stops and errors are reported.

Take a quick look on different compilers — 👉 https://www.codechef.com/wiki/list-compilers

--

--

Syed Zubair

I am a Full-Stack Developer - Nodejs | TypeScript | JavaScript | Mongoose