Skip to content
systemcoding.dev
Security

Build a position-independent executable with -fPIE -pie

Link a PIE with -fPIE -pie on GCC 14 so the kernel can randomise the load address, then confirm it with readelf -h reporting DYN as the file type.

1 min read
Summarize in AI

Address space layout randomisation only moves the main program if the program is built to run at any address. That is what a position-independent executable is: -fPIE makes the compiler emit position-independent code and -pie makes the linker produce an ET_DYN file instead of a fixed-address ET_EXEC. Most current distributions turn both on by default, so this is mainly worth knowing for cross toolchains and for builds that set their own flags.

Shell
gcc -O2 -fPIE -pie main.c -o main
gcc -O2 -fno-pie -no-pie main.c -o main-fixed
readelf -h main | grep Type
readelf -h main-fixed | grep Type
Text
  Type:                              DYN (Position-Independent Executable file)
  Type:                              EXEC (Executable file)

The compile flag and the link flag are separate: object files built without -fPIE fail to link into a PIE with relocation errors, and -fPIE alone still links a fixed-address binary. Use -fPIC for shared libraries and -fPIE for executables, because PIE lets the compiler assume symbols are defined locally and generate slightly tighter code. A fully static PIE needs -static-pie, which GCC has accepted since version 8 and which also needs a glibc built for it. The GCC link options list each spelling.

Also inToolchains
Taggedcgcc
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.