Add gcc or g++ Compiler Options to Binary File

Add gcc or g++ Compiler Options to Binary File

During C or C++ program builds, compiler options can be embedded directly into the resulting executable. This helps with reproducibility, debugging, and later inspection of how a executable was produced. This tutorial explains how to add gcc or g++ compiler options to binary file.

The gcc or g++ compiler options can be recorded inside the output binary by using the -frecord-gcc-switches during compilation. For example:

gcc -O3 -frecord-gcc-switches main.c -o test
g++ -O3 -frecord-gcc-switches main.cpp -o test

When the -frecord-gcc-switches option is enabled, the compiler writes metadata containing the compilation options into a dedicated ELF section.

Once the binary is built, embedded compiler options can be retrieved using ELF inspection utilities such as readelf by reading the .GCC.command.line section.

readelf -p .GCC.command.line test

Output example:

String dump of section '.GCC.command.line':
  [     0]  GNU C17 11.4.0 -mtune=generic -march=x86-64 -O3 -fasynchronous-unwind-tables -fstack-protector-strong -fstack-clash-protection -fcf-protection
String dump of section '.GCC.command.line':
  [     0]  GNU C++17 11.4.0 -mtune=generic -march=x86-64 -O3 -fasynchronous-unwind-tables -fstack-protector-strong -fstack-clash-protection -fcf-protection

The output typically includes multiple layers of build information. It records the active language standard used during compilation, the exact compiler version, and both user-specified options like -O3 as well as additional hardening or target-specific options automatically injected by the compiler, such as -fcf-protection.

Leave a Comment

Cancel reply

Your email address will not be published.