C compilation steps

Use this command to generate files for each of these steps
gcc -Wall -save-temps cprogram.c -o cprogram
The are intermediate files that will be generated from the command:
cprogram.i: generated by preprocessorcprogram.s: generated by compilercprogram.o: generated by assemblercprogram: generated by linker
Now lets take this piece of code and compile it using gcc with the command mentioned above and see what it produces in each step.
#include<stdio.h>
#define x 10
int main(){
//this is a comment
printf("%d", x);
}
Step 1: preprocessor
Preprocessed code:
# 0 "cprogram.c"
# 0 "<built-in>"
# 0 "<command-line>"
....
....
extern FILE *fopen (const char *__restrict __filename,
const char *__restrict __modes)
__attribute__ ((__malloc__)) __attribute__ ((__malloc__ (fclose, 1))) ;
....
....
extern int __uflow (FILE *);
extern int __overflow (FILE *, int);
# 967 "/usr/include/stdio.h" 3 4
# 2 "cprogram.c" 2
# 3 "cprogram.c"
int main(){
// comment is gone
printf("%d", 10); // x is replaced
}
we can also use this command to extract the preprocessed code using gcc:
gcc -E cprogram.c
or this,
cpp cprogram.c
Here cpp means c preprocessor.
So what does preprocessor do?
- Removal of comments
- Macro expansion (here
xis replaced by 10) - Expansion of the included files
- Handling conditional compilation
What is conditional compilation?
Conditional compilation enables us to include or exclude specific sections of code based on certain conditions. We can use directives like#ifdef, #ifndef, #if, #elif, #else, and #endif to conditionally compile code blocks. This feature allows us to adapt our code to different platforms or configurations.Step 2: compilation
compilled code:
.file "cprogram.c"
.text
.section .rodata
.LC0:
.string "%d"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $10, %esi
leaq .LC0(%rip), %rax
movq %rax, %rdi
movl $0, %eax
call printf@PLT
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (GNU) 13.2.1 20230801"
.section .note.GNU-stack,"",@progbits
Use this command to generate assembly code using gcc:
gcc -S cprogram.c
So does compilation step do?
- It checks the syntax and semantics of your code, performs type checking.
- Generate intermediate object code.
Step 3: Assembling
Assembler generated code:
ELF >