How does a compiler compile a compiler?

wtsang02 picture wtsang02 · Jul 11, 2013 · Viewed 8.5k times · Source

Coming from a high-level programming background, I am interested in learning about low-level programming. I want to know how a compiler is compiled?

After looking at some articles in wiki, Numerical machine code is said to be lowest level language, but there has to be a compiler to compile this machine code. What language is that compiler written in?

Answer

cHao picture cHao · Jul 11, 2013

Typically, compiler authors go one of two routes:

  • Write the entire compiler in some other existing language. This is generally the simplest option.

  • Write just enough code in some other language to have a minimally usable translator, and use that "scaffolding" as a base to write the compiler proper in the language it's intended to compile. This is more complicated, and usually takes longer, but inherently offers the chance to flush out language bugs and weaknesses by testing the language in a real project.

The first program to translate code was written at least partly in machine code -- the actual numbers that tell the CPU what to do. It's the lowest level because there is not really a "compiler" for machine code*; it's just numbers arranged a certain way, and the CPU has circuitry within it to process them without outside help.

* There are programs to help design the hardware that interprets and executes the instructions, but that arguably sits outside the definition of a compiler. Such programs generate hardware descriptions -- circuit diagrams and the like -- as opposed to the directly executable files a compiler outputs.