How a Compiler Works

Publication

Pub Details

Date

Pages

See all articles from T-S Horizons n7

A compiler is a program that takes a high level language like BASIC and converts it to machine code. The miracle of a compiler is that people who just have a slight knowledge of machine code can write complex programs that execute much faster than ordinary BASIC programs.

The compiler I have written is itself a BASIC program. It cannot convert itself, however, to machine code, because only certain commands are handled by the compiler and many other commands beside these are used in the process.

The machine code that is produced is simple to understand. The Z80 has over 700 instructions and the compiler probably uses less than 20 of them. In fact, the whole process of compiling is more a matter of record keeping than anything else. I’ve compiled BASIC for years by hand with pencil and paper.

The ability of the compiler to keep track of things really becomes apparent when you consider instructions like “GOTO 100”. In assemble language this might look like “JP 64000”, which is a simple instruction that just takes three bytes, I say “might” because it is a tricky business to know where line 100 would be in memory. It might not be a location 64000, but instead at 62000 or 60000 etc.

To solve this problem the compiler makes two passes through, the BASIC, or to put it another way, it compiles the program twice. The first time through it remembers where each line is compiled to in memory. The second time through it fills in the “JP” instructions with appropriate addresses.

Products

 

Downloadable Media

 
Scroll to Top