100 likes | 276 Views
Compilation Process. COP 3402 (Summer 2013). Compilation process. Break the command "gcc -o test.c ..." into preprocessing, compilation, assembly, and linking. Input Program Output Source code Preprocessor Expanded source
E N D
Compilation Process COP 3402 (Summer 2013)
Compilation process Break the command "gcc -o test.c ..." into preprocessing, compilation, assembly, and linking. InputProgramOutput Source code Preprocessor Expanded source Expanded code Compiler Assembly source Assembly source Assembler Object code Object code Linker Executable code Executable code Loader Execution
A simple program that adds two numbers (not including any library). Example1: Source program (call it test.c) int test_fun(int x) {return x + 17;} int main(void) { int x = 1; int y; y = test_fun(x); return 0; } Example
Step 1: cpp test.c test.i Output: # 1 "test.c" # 1 "<built-in>" # 1 "<command-line>" # 1 "test.c" int test_fun(int x) {return x + 17;} int main(void) { int x = 1; int y; y = test_fun(x); return 0; } Example: Step 1
Step 2: gcc -S test.i -o test.s Output: .file "test.c" .text .globl _test_fun .def _test_fun; .scl 2; .type 32; .endef _test_fun: pushl %ebp movl %esp, %ebp movl 8(%ebp), %eax addl $17, %eax popl %ebp ret .def ___main; .scl 2; .type 32; .endef .globl _main .def _main; .scl 2; .type 32; .endef Example: Step 2
Step 2: gcc -S test.i -o test.s Output continued: _main: pushl %ebp movl %esp, %ebp andl $-16, %esp subl $32, %esp call ___main movl $1, 28(%esp) movl 28(%esp), %eax movl %eax, (%esp) call _test_fun movl %eax, 24(%esp) movl $0, %eax leave ret Example: Step 2 Continued
Step 3: as test.s -o test.o The file contains the machine code for program test Output (Big Endian; viewed with Notepad++ hex editor plugin): Example: Step 3
Step 4: gcc test.o (for linking) and produces a.out a.out is a long file, so it will not be shown here, but you may view it with a hex editor if you follow these steps on your own. Step 5: ./a.out (to load and execute) There will not be any output, but the program should run without error. Example: Steps 4 & 5
Step 1: cpp test.c test.i test.i contains the preprocessed c file Step 2: gcc -S test.i -o test.s test.s contains the assembly code Step 3: as test.s -o test.o test.o contains the machine code Step 4: gcc test.o (for linking) and produces a.out a.out is the ELF file Step 5: ./a.out (to load and execute) Compilation Process Summary
1. Follow the steps of the example on your own. Results may vary. 2. Follow the steps of the example with a simple hello world program that includes I/O, and therefore the standard I/O library, stdio.h: #include <stdio.h> Int main (void) { printf (“Hello, world!\n"); return 0; } Exercises