Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create this file on a Unix system, giving it the name main.c: int main() { retur

ID: 3569560 • Letter: C

Question

Create this file on a Unix system, giving it the name main.c:

       int main() {

         return 0;

}

Figure out how to compile, assemble, and link this into an executable program, not using a one-step command like cc main.c, but using separate steps to compile, assemble, and link. Show the exact commands that are necessary. (Hint: Look at the -v flag on the cc command if you get stuck.) Print out, compare, and hand in the following results:

a.The assembly-language file main.s.

b.The result of disassembling the file main.o (using the dis command).

c.The result of disassembling the final a.out file (using the dis command).

These three print-outs are quite different. How do you account for the differences?

Explanation / Answer

main.c file:

int main(){
   return 0;
}

1.
a) Preprocessing: This is the first stage of compilation process where preprocessor directives (macros and header files are most common) are expanded. To perform this step gcc executes the following command internally

cmd: cc -P <program>.C > <program>.i
Eg.
[root@host ~]# cc -P main.c > main.i

b) Compilation: Tells the compiler to convert the preprocessed code to assembly language without creating an object file with extension ".s"

cmd: cc -S <program>.i
Eg.
[root@host ~]# cc -S main.i

c) Assembly: Here, the assembler (as) translates object file into machine language instructions, and generates another object file.

cmd: cc -c <program>.i
Eg.
[root@host ~]# cc -c <program>.i

d) Linking: This is the final stage in compilation of program. This phase links object files to produce final executable file. An executable file requires many external resources (system functions, C run-time libraries etc.).

Two ways:
1. After compilation
cmd: cc <program>.s
[root@host ~]# cc main.s

2. After assembling
cmd: cc <program>.o
[root@host ~]# cc main.o
Creates a.out file.

e) Finally the executable program is created and can be executed as below:
./main

b. Assembly language code for main.o

$ gdb main.o
(gdb) disas main
Dump of assembler code for function main:
0x0000000100000f30 <main+0>: push %rbp
0x0000000100000f31 <main+1>: mov %rsp,%rbp
0x0000000100000f34 <main+4>: mov $0x0,%eax
0x0000000100000f39 <main+9>: movl $0x0,-0x4(%rbp)
0x0000000100000f40 <main+16>: pop %rbp
0x0000000100000f41 <main+17>: retq   
End of assembler dump.