The 2-pass compilers
Two-pass
compilers:
- A 2-pass compiler
reads the
source code
twice
to compile (= translate)
a program
- In the
1st pass, the
compiler will:
-
Gather
the
type information of
all
variables and
functions
|
- In the
2nd pass, the
compiler will:
-
Use
the
type information on
the
variables and
functions to
translate
the computer program
|
- Advantage
of a 2-pass compiler:
- Programmers can
define
variables
after the
statements that
use the
variable
|
|
Example of a two-pass compiler:
Java
- The Java compiler is
a
2-pass compiler
|
Evidence:
the Java compiler can
compile this
code:
public class demo
{
public static void main(String[] args)
{
System.out.println(x); // How can Java compiler know
// which overloaded method to call ?
} // Answer: read input file twice !
static int x = 1234;
}
|
DEMO:
/home/cs255001/demo/C/set1/java2pass.java
The 1-pass compilers
One-pass
compilers:
- A 1-pass compiler
reads the
source code
once
to compile (= translate)
the program
- In the one-pass compiler,
the compiler will:
- Gather the
definition of
all
variables and
functions
while it is
translating the
program !!!
|
|
Notable fact about
1 pass compilers:
-
All variables
must be
defined
before a
statement that
uses the
variables
|
Example of a one-pass compiler:
C
- The C compiler is
a
1-pass compiler
|
Evidence:
the C compiler
can
compile this
code:
#include <stdio.h>
int x = 1234;
int main( )
{
printf("%d\n", x);
}
|
DEMO:
/home/cs255001/demo/c/set1/c-1pass.c
Example of a one-pass compiler:
C
- The C compiler is
a
1-pass compiler
|
Evidence:
the C compiler can
not
compile this
code:
#include <stdio.h>
int main( )
{
printf("%d\n", x); // <-- error !
}
int x = 1234;
|
Reason:
the data type of
x is
not (yet) known
when the C compiler
processes the
highlight line !!
Pros and cons of 1-pass and 2-pass compilers
- 2-pass
compilers
(e.g.:
Java):
- Pro:
convenience for
programmers
- Con:
longer
compilation time
|
- 1-pass
compilers
(e.g.:
C):
- Pro:
shorter
compilation time
- Con:
clumbersome:
- Specifically: the
C language needs to
use
declarations to
convey the
data type information
of (global) variables
and function prototypes
|
|
|
❮
❯