Compiler: A short note
A compiler translates human-readable code (C, C++, Python) into machine code that a computer can execute. But not all compiled code is the same, though done by same compiler.
Because of these two instructions:-
-march=
→ Generate machine code for a specific CPU architecture.-mtune=
→ Optimize code to run better on a particular CPU, while staying compatible with others.
The Compiler’s Work:
Preprocessing: Expands macros and includes files.
Compilation: Converts high-level code into intermediate code.
Optimization: Tweaks the code for better performance.
Assembly: Translates optimized code into machine instructions.
Linking: Combines all compiled parts into an executable program.
Optimization Levels (-O Flags)
Flag | Purpose |
-O0 | No optimization (easier debugging) |
-O1 | Basic optimizations for better speed |
-O2 | Default optimization for balance |
-O3 | Maximum optimization for performance |
-Os | Optimizes for smaller file size |
-Ofast | Ignores some rules for extreme speed |
Trade-offs in Optimization
Compiler optimizations improve speed, size, and efficiency, but choosing the right level involves trade-offs:
-O0
is best for debugging (more readable code, but slower execution).-O3
gives max speed (but can make debugging harder).-Os
reduces file size, which is useful for embedded systems.