A computer's processor only understands machine code, so every program written in Python, C# or Go has to be translated before it can run. A compiler and an interpreter are two different answers to 'when does that translation happen?', and the answer shapes how fast your program runs, when you find your mistakes and how you ship your code.
The same job, two timetables
Both tools take source code, the text you write, and turn it into something the machine can act on. Neither is better in general. They make different trade-offs about when the work is done.
- A compiler translates the whole program first, producing a new file (an executable, or some intermediate form). Running the program is a separate step that can happen later, as many times as you like.
- An interpreter reads your program and carries out each instruction as it goes. There is no finished translation left behind: the next time you run the program, the interpreter reads it again.
The rest of the differences follow from that one choice.
How a compiler works
A compiler reads all of your source code before anything runs. Roughly, it:
- Splits the text into tokens: keywords, names, numbers, symbols.
- Parses those tokens into a tree that captures the program's structure.
- Checks the tree for errors it can prove, such as a call to a function that doesn't exist or, in a statically typed language, a string where a number should be.
- Optimises the code, for example by working out constant expressions once or removing code that can never run.
- Writes out the result, often machine code for one kind of processor and operating system.
The output is a standalone program. Your users run that file, not your source code, and they don't need the compiler installed. The expensive part, the translation and optimisation, is paid once at build time. Every run after that starts from ready-made machine code, which is why compiled programs are usually fast.
Wondering how this was made? How we make these