GCC: compile options to harden a C/C++ binary
Common GCC hardening options (FORTIFY_SOURCE, stack protector, PIE, RELRO) with a reference link.
GCC offers many compile options that harden C/C++ binaries against memory-safety flaws. A reference discussion on the topic: What is the most hardened set of options for GCC compiling C/C++?.
Common option examples
gcc -O2 -D_FORTIFY_SOURCE=2 -fstack-protector-strong -fPIE -pie -Wl,-z,relro,-z,now -o app app.c
| Option | Effect |
|---|---|
-D_FORTIFY_SOURCE=2 |
Extra checks on string/memory functions (needs -O1 or higher) |
-fstack-protector-strong |
Stack canary on risky functions |
-fPIE -pie |
Position-independent executable (ASLR-friendly) |
-Wl,-z,relro,-z,now |
Eager symbol binding and read-only GOT |
Notes
- The options in the table were added from general knowledge; the source note only held the link. See the linked discussion for a complete, up-to-date list.