Modern Compilation
Compilation Workflow
graph TD
A[Source Code] --> B[Preprocessor]
B --> C[Compiler]
C --> D[Assembler]
D --> E[Linker]
E --> F[Executable]
Preprocessing Stage
Macro Expansion
#define MAX_SIZE 100
#define SQUARE(x) ((x) * (x))
int main() {
int array[MAX_SIZE];
int result = SQUARE(5);
return 0;
}
Preprocessing command:
gcc -E program.c > preprocessed.c
Compilation Stages
Stage |
Description |
Tool |
Preprocessing |
Macro expansion, file inclusion |
cpp |
Compilation |
Convert to assembly |
gcc |
Assembly |
Convert to object code |
as |
Linking |
Create executable |
ld |
Advanced Compilation Techniques
Separate Compilation
#ifndef HEADER_H
#define HEADER_H
int calculate(int a, int b);
#endif
math.c
#include "header.h"
int calculate(int a, int b) {
return a + b;
}
main.c
#include <stdio.h>
#include "header.h"
int main() {
int result = calculate(5, 3);
printf("Result: %d\n", result);
return 0;
}
Compilation process:
gcc -c math.c ## Create object file
gcc -c main.c ## Create object file
gcc math.o main.o -o program ## Link object files
Modern Compilation Flags
Optimization and Debugging
## Compile with optimization and debug symbols
gcc -O2 -g program.c -o program
## Enable all warnings
gcc -Wall -Wextra -Werror program.c -o program
Static and Dynamic Linking
graph TD
A[Static Linking] --> B[Entire Library Copied]
A --> C[Larger Executable]
D[Dynamic Linking] --> E[Library Referenced]
D --> F[Smaller Executable]
Static Library Creation
## Create static library
gcc -c library.c
ar rcs libmylib.a library.o
## Link with static library
gcc main.c -L. -lmylib -o program
Dynamic Library Creation
## Create shared library
gcc -shared -fPIC library.c -o libmylib.so
## Link with shared library
gcc main.c -L. -lmylib -o program
Cross-Compilation
## Cross-compile for ARM
arm-linux-gnueabihf-gcc program.c -o program_arm
LabEx Best Practices
- Use modern compiler standards
- Enable comprehensive warnings
- Utilize optimization flags
- Implement separate compilation
- Understand linking mechanisms
Conclusion
Modern compilation techniques provide developers with powerful tools to create efficient, portable, and robust C programs across various platforms and environments.