Most C and C++ binaries ship with weaker protection than their platform supports, because GCC and Binutils upstream do not enable hardening by default and every distribution, SDK and CI image configures different defaults. A handful of compiler and linker options, such as _FORTIFY_SOURCE, stack protectors, RELRO, PIE and control-flow protection, turn whole classes of memory bugs into crashes instead of exploits, and warning options catch many of the bugs before they ship. This guide turns the OpenSSF Compiler Options Hardening Guide for C and C++ and the equivalent Microsoft toolchain options into a practical programme: which flags to set, what each one does and costs, how to roll them out in an existing codebase, how to verify the binaries you actually ship, and how to protect the toolchain itself. It is for build and release engineers, C and C++ developers, product security teams and anyone who buys or packages native software.
Key takeaways
- Set flags explicitly in the build system. OpenSSF recommends not relying on toolchain defaults, which vary by distribution and vendor; check what your compiler actually uses with
cc -v. - Two kinds of flags do different jobs. Compile-time warnings (
-Wall,-Wformat=2,-Wconversion) find defects with no run-time cost; run-time options (-D_FORTIFY_SOURCE=3,-fstack-protector-strong,-fcf-protection=full) make surviving bugs harder to exploit. - Hardening only covers code you compile. Prebuilt third-party libraries keep whatever protection their vendor gave them, so verify every shipped binary, not just your own modules.
- Verify the output, not the makefile. Binary analysers such as Microsoft BinSkim check the shipped PE and ELF files for ASLR, NX, stack protection, CFG, shadow-stack compatibility and more, and fit in CI as a release gate.
- The toolchain is part of your supply chain. A compromised compiler, build script or CI runner can insert code that no flag will catch; pin, verify and isolate it.
Why compiler hardening matters
OpenSSF states its threat model plainly: all developers make mistakes, some of those mistakes become vulnerabilities, and memory safety issues cause most vulnerabilities in C and C++ code. Compiler hardening has three objectives in the OpenSSF guide: minimise the likelihood and impact of vulnerabilities released in production code, maximise detection during compilation and test, and detect underhanded code such as Trojan Source where practical. It is not a substitute for memory-safe languages, review, fuzzing or design; it is the cheapest layer of defence in depth for code that must remain in C or C++. See the C and C++ Secure Coding Guide for coding practices and the Memory-Safe Languages Guide for the longer-term route.
Run-time options fall into two groups, in the OpenSSF taxonomy: options that add checks to the generated code to detect memory errors (fortification, stack protectors, library assertions), and options that make the binary compatible with operating system protections (PIE for ASLR, non-executable stack for DEP, RELRO, CET and branch protection markings). The second group is what lets the platform mitigations described in the Exploit Mitigations Guide work at all.
The recommended baseline for GCC and Clang
The OpenSSF guide (version dated 20 August 2026 when checked on 27 October 2026) gives a baseline to turn on in all cases, plus additions per situation. The table summarises the run-time and linker options; support versions are as the guide states them.
| Option | What it does | Supported since (per OpenSSF) | Cost or caveat |
|---|---|---|---|
-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3 | Compile- and run-time checks on glibc functions such as memcpy, strcpy and sprintf; level 3 also checks when buffer size is only known as an expression | GCC 12, Clang 9 | Requires -O1 or higher (-O2 recommended); Clang fortification of glibc calls has had gaps |
-D_GLIBCXX_ASSERTIONS / -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST | Precondition checks in the GNU and LLVM C++ standard libraries (for example bounds on container access) | libstdc++ 6, libc++ 18.1 | Can affect performance |
-fstack-protector-strong | Stack canaries on functions with local arrays or address-taken locals | GCC 4.9, Clang 6 | Small overhead |
-fstack-clash-protection | Checks variable-size stack allocations so the stack cannot jump over guard pages | GCC 8, Clang 11 | Small overhead |
-fstrict-flex-arrays=3 | Treats only [] trailing arrays as flexible, improving bounds checking | GCC 13, Clang 16 | May require code changes for old idioms |
-fcf-protection=full (x86_64) | Emits Intel CET instrumentation for indirect branch tracking and shadow-stack compatibility | GCC 8, Clang 7 | Effective only on CET-capable hardware and OS |
-mbranch-protection=standard (AArch64) | Arm Pointer Authentication and Branch Target Identification | GCC 9, Clang 8 | Instructions are no-ops on older cores |
-fzero-call-used-regs=used-gpr | Zeroes used registers on return, limiting data lifetime and ROP gadgets | GCC 11, Clang 16 | Can affect performance |
-fPIE -pie (executables) / -fPIC -shared (libraries) | Position-independent code so ASLR can randomise the image | Binutils 2.16, Clang 5 | Overhead mainly on 32-bit |
-Wl,-z,relro -Wl,-z,now | Full RELRO: relocation entries resolved at load time and marked read-only | Binutils 2.15 | now can slow start-up |
-Wl,-z,noexecstack | Marks the stack non-executable | Binutils 2.14 | Breaks code needing executable trampolines (warned by -Wtrampolines) |
-Wl,-z,nodlopen | Restricts dlopen of the object | Binutils 2.10 | Not for plug-in libraries meant to be loaded |
-ftrivial-auto-var-init=zero, -fno-delete-null-pointer-checks, -fno-strict-overflow, -fno-strict-aliasing | Production-code options that remove classes of undefined-behaviour surprises | Various (GCC 12 and Clang 8 for auto-var-init) | Some optimisation loss |
Warnings in the baseline: -Wall -Wformat -Wformat=2 -Wconversion -Wimplicit-fallthrough -Werror=format-security, plus -Wtrampolines and -Wbidi-chars=any on GCC, and -Werror=implicit -Werror=incompatible-pointer-types -Werror=int-conversion for C. OpenSSF recommends blanket -Werror during development but not when distributing source, because it ties builds to specific compiler versions.
The umbrella option: GCC 14 added -fhardened, which enables a predetermined set of hardening options on GNU/Linux; --help=hardened shows the exact set for your version. The GCC manual lists -D_FORTIFY_SOURCE=3 (level 2 with glibc older than 2.35), -D_GLIBCXX_ASSERTIONS, -ftrivial-auto-var-init=zero, PIE with full RELRO, -fstack-protector-strong, -fstack-clash-protection and, on x86 GNU/Linux, -fcf-protection=full. OpenSSF notes that options given explicitly on the command line take precedence, so -fstack-protector -fhardened ends up with the weaker protector, and -Whardened warns when this happens.
Discouraged: OpenSSF lists -Wl,-rpath as discouraged in release binaries, because a hard-coded run-time search path (especially relative paths or $ORIGIN, and above all in setuid programs) can let an attacker supply a malicious shared library.
Microsoft toolchain equivalents
| Option (MSVC compiler or linker) | Protection | BinSkim rule that checks it |
|---|---|---|
/GS | Stack buffer overrun detection (security cookie) | BA2011 EnableStackProtection |
/sdl | Superset of /GS checks: strict GS, pointer sanitisation after delete, member pointer initialisation, and warnings such as C4700 (uninitialised local) and C4789 (buffer overrun in CRT calls) as errors. Off by default at compiler level | BA2026 EnableMicrosoftCompilerSdlSwitch |
/guard:cf | Control Flow Guard: checks indirect call targets at run time | BA2008 EnableControlFlowGuard |
/DYNAMICBASE | Image eligible for ASLR relocation | BA2009 EnableAddressSpaceLayoutRandomization |
/HIGHENTROPYVA | High-entropy 64-bit ASLR | BA2015 EnableHighEntropyVirtualAddresses |
/NXCOMPAT | Data Execution Prevention compatibility | BA2016 MarkImageAsNXCompatible |
/CETCOMPAT (x64, Visual Studio 2019 onwards) | Marks the image compatible with CET shadow stacks | BA2025 EnableShadowStack |
BinSkim's shadow-stack rule notes that older .NET runtimes (.NET 6 or earlier) are not compatible with CET shadow stacks, so a native host that loads older managed assemblies needs testing before you mark it compatible. BinSkim also includes ELF rules for Linux builds, such as BA3001 EnablePositionIndependentExecutable, BA3003 EnableStackProtector, BA3010 EnableReadOnlyRelocations, BA3011 EnableBindNow and BA3030 UseGccCheckedFunctions.
Instrumented test builds and sanitizers
OpenSSF distinguishes production code from instrumented test code, and recommends testing both. Sanitizers belong in the second.
- AddressSanitizer (
-fsanitize=address): out-of-bounds and use-after-free detection. - UndefinedBehaviorSanitizer (
-fsanitize=undefined): integer overflow, invalid shifts, misaligned access and similar. - ThreadSanitizer (
-fsanitize=thread) and LeakSanitizer (-fsanitize=leak): data races and leaks. - Not for production: OpenSSF warns against using sanitizers to harden production binaries, particularly setuid programs, because their runtime reads environment variables that can be abused; the exception is UBSan in minimal-runtime or trap mode.
- Pair with fuzzing: sanitizers turn silent corruption into reproducible crashes, which is what makes fuzzing effective. See the Fuzzing Guide.
Rolling out hardening in an existing codebase
OpenSSF advises enabling everything at once on green-field projects, and on brown-field projects enabling one or a few options at a time, assessing impact, fixing problems and repeating. A workable sequence:
- Record the current state: capture effective flags (
cc -v,cc -O2 -dM -E - < /dev/nullfor predefined macros, including any default_FORTIFY_SOURCElevel) and run a binary analyser over current release artefacts. - Centralise flags: put hardening flags in one place in the build system (CMake toolchain file, Meson options, MSBuild property sheet) rather than scattered per target, and mark third-party headers as system headers (
-isystem) so warning levels can be raised without noise. - Linker and layout options first: PIE, RELRO and now, noexecstack,
/DYNAMICBASE,/NXCOMPATand/HIGHENTROPYVArarely change behaviour of correct code. - Then run-time checks: stack protector and stack clash protection, then
_FORTIFY_SOURCE=3and library assertions. Run the full test suite and benchmarks after each step; OpenSSF notes applications that misusemalloc_usable_sizecan abort under fortification level 3. - Then control-flow options:
-fcf-protection=fullor-mbranch-protection=standard,/guard:cfand/CETCOMPAT, tested on capable hardware with the operating system enforcement enabled. - Warnings to errors selectively: promote specific warnings with
-Werror=<flag>once the codebase is clean of them. - Gate releases: run the binary analyser in CI on every release artefact and fail the build on regressions.
- Rollback: because flags are centralised, reverting one option is a single change. Revert only the option that caused a regression and file the root cause; do not drop the whole hardening profile.
Choosing what to apply where
| Situation | Approach |
|---|---|
| New project | Full OpenSSF baseline plus situational options from the start; blanket -Werror in CI |
| Large legacy codebase | Staged rollout as above; prioritise internet-facing parsers and privileged components |
| Performance-critical code | Benchmark each option; OpenSSF notes that omitting options is defensible only where the program processes trusted data |
| Embedded and IoT | Watch binary size and older toolchains; verify the vendor SDK compiler version supports the options. See the Embedded Linux and Yocto Hardening Guide |
| Linux distribution or internal package builds | Use the distribution's hardening build flags mechanism, and consider building compilers with secure defaults (--enable-default-pie, --enable-default-ssp) and Binutils with --enable-error-execstack and --enable-error-rwx-segments |
| Buying native software | Ask vendors for binary analysis results (ASLR, NX, CFG or CET, stack protection) for every shipped module |
Protecting the toolchain and build
Hardening flags assume the compiler and build scripts are honest. The XZ Utils backdoor showed the gap: the payload was not in the git source but in release tarballs, in a modified build-to-host.m4 build macro and binary test files, and the altered build script inserted it into liblzma during compilation.
- Pin and verify toolchains: install compilers and SDKs from signed packages or verified container images, pin versions, and record them in build provenance. See the SLSA and Build Provenance Guide.
- Build from reviewed source: generate build scripts from version control rather than trusting generated files in release tarballs, and compare tarball contents with the tagged source.
- Reproducible builds: independent rebuilds that produce identical binaries detect a tampered toolchain or build host. See the Reproducible Builds Guide.
- Isolate build runners: ephemeral runners, no long-lived credentials, separation between untrusted pull request builds and release builds.
- Keep debug information separate: OpenSSF describes stripping symbols from shipped binaries and keeping debug information in separate files with a debug link, which keeps crash analysis possible without shipping full symbols.
Where identity fits
The release build is where signing keys, package registry tokens and cloud credentials meet the toolchain. A hardened binary signed by a stolen code signing key, or published with a leaked registry token, is still a malicious release. Treat CI runner identities, signing keys and publishing tokens as privileged non-human identities: short-lived, scoped to the release job, and held in a vault or hardware security module rather than in build variables. See the CI/CD Pipeline Identity Security Guide and the Compromised Code Signing Certificate Playbook.
Detection and measurement
- Binary analysis in CI: SARIF output from BinSkim (or equivalent ELF checks) per artefact, trended over releases.
- Fortify and canary aborts in the field:
_FORTIFY_SOURCEand stack protector failures print an error and terminate the process. Collect crash reports and treat these abort signatures in internet-facing components as potential exploitation, not just bugs. - Toolchain drift: alert when a build uses a compiler version or image digest other than the pinned one.
Metrics:
- Percentage of shipped binaries passing all hardening checks (ASLR or PIE, NX, stack protection, RELRO and now, CFG or CET where applicable).
- Number of third-party prebuilt modules failing checks, and the age of each exception.
- Percentage of builds using the centralised hardening profile and the pinned toolchain.
- Count of compiler warnings per thousand lines in hardened warning configuration, trending down.
- Percentage of fuzzing and test runs executed with sanitizers.
Framework mapping
| Framework | Reference | Relevance |
|---|---|---|
| NIST SP 800-53 Rev. 5 | SA-15 Development Process, Standards, and Tools; SA-11 Developer Testing and Evaluation; SI-16 Memory Protection; SR-4 Provenance; CM-14 Signed Components | Hardened toolchain configuration, sanitizer and analysis testing, memory protection, toolchain provenance and signed releases |
| NIST CSF 2.0 | PR.PS-06 Secure software development practices are integrated and monitored | Hardening profile and release gates |
| NIST SSDF (SP 800-218) | Secure build and tooling practices | See the NIST Secure Software Development Framework (SSDF, SP 800-218) Guide |
| MITRE D3FEND | D3-SFCV Stack Frame Canary Validation; D3-SAOR Segment Address Offset Randomization; D3-PAN Pointer Authentication | Defensive techniques enabled by the flags |
Common failure patterns
- Trusting toolchain defaults: a build that relied on a distribution's default hardening loses it when moved to a different base image or cross-compiler.
- Flag ordering accidents: a later
-U_FORTIFY_SOURCE, a weaker-fstack-protectorafter-fhardened, or-O0silently disable protections. OpenSSF notes that the later occurrence of a repeated option usually wins. - Hardening your code, shipping theirs: prebuilt vendor libraries without ASLR or NX are linked into otherwise hardened products.
- Sanitizers in production: AddressSanitizer builds shipped to customers, including setuid tools, adding attack surface instead of removing it.
- Executable stacks from assembly: a single assembly file without a GNU-stack note makes the whole binary's stack executable; Binutils 2.39 and later can warn and 2.42 can error on this.
- Build scripts outside review: generated configure scripts and macros in release archives are trusted without comparison to source, the gap the XZ Utils attacker used.
Practitioner checklist
- Adopt the OpenSSF baseline flags explicitly in a central build configuration for GCC and Clang.
- Set
/GS,/sdl,/guard:cf,/DYNAMICBASE,/HIGHENTROPYVA,/NXCOMPATand/CETCOMPATfor MSVC builds after compatibility testing. - Add
-fcf-protection=fullon x86_64 and-mbranch-protection=standardon AArch64. - Use
-D_FORTIFY_SOURCE=3with-O2, preceded by-U_FORTIFY_SOURCE. - Run sanitizer-instrumented builds in tests and fuzzing; never ship them as production hardening.
- Gate every release on binary analysis of all shipped modules, including third-party ones.
- Pin and verify compilers, SDKs and build images, and record them in provenance.
- Remove
-rpathfrom release binaries, especially setuid programs. - Protect signing keys and publishing tokens used by release builds as privileged non-human identities.
Standards and references
- OpenSSF: Compiler Options Hardening Guide for C and C++
- GCC: Program Instrumentation Options
- LLVM: Clang Control Flow Integrity
- Microsoft Learn: /sdl (Enable Additional Security Checks)
- Microsoft Learn: /CETCOMPAT (CET Shadow Stack compatible)
- Microsoft: BinSkim Binary Analyzer rules
- NIST: SP 800-218 Secure Software Development Framework
Related NHI Mgmt Group resources: C and C++ Secure Coding Guide · Exploit Mitigations Guide · Memory-Safe Languages Guide · Reproducible Builds Guide · CI/CD Pipeline Identity Security Guide