The CPU can only run machine code. A high-level program must first be changed into machine code. The software that does this is a translator 翻译程序. There are three types: a compiler and an interpreter (for high-level code), and an assembler (for low-level code).
Compiler
A compiler translates the whole program into machine code before it is run. After translating, the machine code can be run many times without translating again.
- translation happens once, in full;
- it reports all the errors together, at the end of translating;
- the finished program runs fast and does not need the compiler to run.
Interpreter
An interpreter 解释器 translates and runs the program one line at a time.
- it stops at the first error it finds, which helps when testing;
- the program runs more slowly, because it is translated each time it runs;
- the interpreter must be present every time the program runs.
|
Compiler |
Interpreter |
| Translates |
the whole program at once |
one line at a time |
| Errors |
all reported at the end |
stops at the first error |
| Speed of finished program |
faster |
slower |
| Needed to run later? |
no |
yes |
Use a compiler when you want to share a fast, finished program. Use an interpreter when you are writing and testing a program and want to find errors easily.
Assembler
An assembler 汇编器 translates a low-level assembly-language program (written in mnemonics such as LDA, ADD) into machine code. Each mnemonic becomes one machine instruction — a direct one-to-one translation, unlike a compiler or interpreter, which work on high-level code.
A compiler translates the whole program once into machine code; an interpreter translates and runs one line at a time
Worked example. A team is writing a program. While developing it they want to find and fix errors quickly; when they ship it they want customers to run it fast without seeing the source code. Which translator suits each stage? While developing, use an interpreter: it translates and runs one line at a time and stops at the first error, so a mistake is easy to locate. To ship, use a compiler: it translates the whole program once into machine code, which then runs quickly with no translator present, and the customer receives only the executable rather than the source. The two are not rivals - name the stage and give the reason, because "a compiler is faster" on its own earns nothing.