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:

  1. Preprocessing: Expands macros and includes files.

  2. Compilation: Converts high-level code into intermediate code.

  3. Optimization: Tweaks the code for better performance.

  4. Assembly: Translates optimized code into machine instructions.

  5. Linking: Combines all compiled parts into an executable program.

Optimization Levels (-O Flags)

FlagPurpose
-O0No optimization (easier debugging)
-O1Basic optimizations for better speed
-O2Default optimization for balance
-O3Maximum optimization for performance
-OsOptimizes for smaller file size
-OfastIgnores 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.