Pass 2 Explanation
Pass 2 Explanation
Code Explanation
Header Files and Global Variables
# include < stdio .h >
# include < stdlib .h >
# include < string .h >
FILE * f1 , * f2 , * f3 , * f4 , * f5 , * f6 ;
int s = -1 , o = -1 , i , j ;
• We include standard input-output, standard library, and string handling header files.
• We declare file pointers for handling multiple files.
• We declare global variables for iterating through symbol and operation tables.
Structure Definitions
struct symt {
char label [30] , addr [30];
} st [30];
struct optt {
char code [30] , mine [30];
} ot [30];
• We define two structures, symt for the symbol table and optt for the operation table.
• Each structure has two fields: label and addr for the symbol table, and code and mine for the
operation table.
void opt () {
while (1) {
o ++;
fscanf ( f2 , " % s % s " , ot [ o ]. code , ot [ o ]. mine );
if ( fgetc ( f2 ) == EOF ) break ;
}
}
• The sym() function reads the symbol table from a file and stores it in the st array.
• The opt() function reads the operation table from a file and stores it in the ot array.
Main Function
void main () {
char label [20] , opcode [20] , operand [30] , a [20] , ad [30];
int address , length , start ;
f1 = fopen ( " intermediate . txt " , " r " );
f2 = fopen ( " optab . txt " , " r " );
f3 = fopen ( " symtab . txt " , " r " );
f4 = fopen ( " len . txt " , " r " );
f5 = fopen ( " output . txt " , " w " );
f6 = fopen ( " objcode . txt " , " w " );
opt ();
sym ();
• We declare local variables for labels, opcodes, operands, addresses, and lengths.
• We call the opt() and sym() functions to read the operation and symbol tables.
• If the opcode is START, we write the header record to the object code file and store the starting
address.
• We initialize the text record, text start address, and text length.
• We start a loop to process each line of the intermediate file until the END opcode is encountered.
• For the BYTE directive, we handle both character and hexadecimal representations.
• For the WORD directive, we convert the operand to an integer using strtol.
• For RESB and RESW directives, we handle reserved space and write out any pending text records.
• For other opcodes, we find the corresponding object code and address from the operation and symbol
tables.
Final Steps
if ( text_length > 0) {
fprintf ( f6 , " T ^%06 X ^%02 X % s \ n " , text_start , text_length , text_record );
}
fprintf ( f5 , " % x \ t % s \ t % s \ t % s \ n " , address , label , opcode , operand );
fprintf ( f6 , " \ nE ^%06 X \ n " , start );
• We write the end record to the object code file with the starting address.