Harden a CMake Project With Security Compiler Flags
Add stack protector, fortify, PIE, full RELRO and CET flags to a CMake 3.28 project with feature checks, per-target options and a verification step.

Hardening flags do nothing if they never reach the compiler. In a CMake project the common failure is a flag added to CMAKE_C_FLAGS in one place, overridden on the command line in another and ignored by a vendored subproject in a third. A reliable setup tests each flag against the actual compiler, applies it per target and not globally, handles the -D_FORTIFY_SOURCE and optimization interaction and is verified on the built binary. This post builds that setup in one CMake module, uses it from a small project and ends with a check that fails the build when a protection is missing. Examples target CMake 3.28, GCC 15 and Clang 20 on Linux 6.12 with glibc 2.41.
What to add
The set below matches the earlier posts in this series. It is the baseline recommended by hardening guides such as the OpenSSF compiler options guide for C and C++.
| Purpose | Compile flags | Link flags |
|---|---|---|
| stack canary | -fstack-protector-strong | |
| fortified libc | -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3 (needs optimization) | |
| stack clash | -fstack-clash-protection | |
| CET and BTI | -fcf-protection=full on x86, -mbranch-protection=standard on AArch64 | |
| position independence | -fPIE | -pie |
| relro and bind now | -Wl,-z,relro,-z,now | |
| non-executable stack | -Wl,-z,noexecstack | |
| warnings as errors for the security ones | -Wformat=2 -Werror=format-security | |
| trivial var init | -ftrivial-auto-var-init=zero (GCC 12, Clang 8) | |
| hardened C++ library | -D_GLIBCXX_ASSERTIONS (libstdc++) |
Each line needs a check that the compiler accepts it, because an unknown flag is a hard error with GCC and a warning with Clang, and the architecture-specific ones only exist on their targets.
The module
Put this in cmake/Hardening.cmake:
include_guard(GLOBAL)
include(CheckCompilerFlag)
include(CheckLinkerFlag)
include(CheckPIESupported)
check_pie_supported(LANGUAGES C CXX)
function(_hardening_try_compile lang flag out)
string(MAKE_C_IDENTIFIER "HARDEN_${lang}_${flag}" var)
check_compiler_flag(${lang} "${flag}" ${var})
set(${out} ${${var}} PARENT_SCOPE)
endfunction()
function(harden_target tgt)
set(opts "")
foreach(flag
-fstack-protector-strong
-fstack-clash-protection
-fcf-protection=full
-mbranch-protection=standard
-ftrivial-auto-var-init=zero
-Wformat=2
-Werror=format-security)
_hardening_try_compile(C "${flag}" ok)
if(ok)
list(APPEND opts ${flag})
endif()
endforeach()
target_compile_options(${tgt} PRIVATE ${opts})
#[[ _FORTIFY_SOURCE only works when optimizing. ]]
target_compile_options(${tgt} PRIVATE
$<$<NOT:$<CONFIG:Debug>>:-U_FORTIFY_SOURCE>
$<$<NOT:$<CONFIG:Debug>>:-D_FORTIFY_SOURCE=3>)
set_target_properties(${tgt} PROPERTIES POSITION_INDEPENDENT_CODE ON)
get_target_property(type ${tgt} TYPE)
if(type STREQUAL "EXECUTABLE")
if(CMAKE_C_LINK_PIE_SUPPORTED)
set_target_properties(${tgt} PROPERTIES POSITION_INDEPENDENT_CODE ON)
endif()
endif()
check_linker_flag(C "LINKER:-z,relro,-z,now" HARDEN_RELRO_NOW)
if(HARDEN_RELRO_NOW)
target_link_options(${tgt} PRIVATE "LINKER:-z,relro,-z,now")
endif()
check_linker_flag(C "LINKER:-z,noexecstack" HARDEN_NOEXECSTACK)
if(HARDEN_NOEXECSTACK)
target_link_options(${tgt} PRIVATE "LINKER:-z,noexecstack")
endif()
endfunction()A few details matter. check_compiler_flag is in the CheckCompilerFlag module, available since CMake 3.19, and takes the language, the flag and a result variable, which it caches. check_linker_flag (CMake 3.18) does the same for the linker, and the LINKER: prefix lets CMake translate the option to the form the compiler driver needs, here -Wl,. check_pie_supported (CMake 3.14) sets CMAKE_C_LINK_PIE_SUPPORTED, and setting POSITION_INDEPENDENT_CODE on an executable target makes CMake add -fPIE and -pie when supported. Since the flags are tested against the compiler that CMake found, an AArch64-only flag is silently skipped on x86 and the reverse.
The fortify definitions use a generator expression so Debug builds, which usually run at -O0, skip them and avoid the "requires optimization" warning. RelWithDebInfo and Release get them.
Using it
cmake_minimum_required(VERSION 3.28)
project(demo LANGUAGES C)
set(CMAKE_C_STANDARD 17)
set(CMAKE_C_STANDARD_REQUIRED ON)
include(cmake/Hardening.cmake)
add_library(core STATIC src/core.c)
add_executable(demo src/main.c)
target_link_libraries(demo PRIVATE core)
harden_target(core)
harden_target(demo)Apply it to every target you build, including static libraries, since their objects are linked into the executable and an unprotected object undermines it. A static library needs -fPIE or -fPIC objects to link into a PIE, and POSITION_INDEPENDENT_CODE ON takes care of that. Third-party code added with add_subdirectory is a separate case: call harden_target on its targets after the fact, or set CMAKE_C_FLAGS before adding it if you cannot touch its files.
Configure and build in Release mode:
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release-- The C compiler identification is GNU 15.1.0
-- Performing Test HARDEN_C__fstack_protector_strong
-- Performing Test HARDEN_C__fstack_protector_strong - Success
-- Performing Test HARDEN_C__fstack_clash_protection - Success
-- Performing Test HARDEN_C__fcf_protection_full - Success
-- Performing Test HARDEN_C__mbranch_protection_standard
-- Performing Test HARDEN_C__mbranch_protection_standard - Failed
-- Performing Test HARDEN_C__ftrivial_auto_var_init_zero - Success
-- Performing Test HARDEN_LINKER_RELRO_NOW - Success
-- Configuring done (0.4s)
-- Generating done (0.0s)The exact result names follow the identifier that the module builds, and the timings differ. The Failed line for -mbranch-protection=standard is correct on x86-64, where the flag does not exist, and the module skips it. Run cmake --build build -v once to see the real command lines and confirm that each target has the flags.
Overriding variables
Users and distributions sometimes pass -DCMAKE_C_FLAGS=... on the command line. Because the module uses per-target options, they add to those flags and do not replace them, which is the reason to prefer target_compile_options over assigning CMAKE_C_FLAGS. A packaging system that appends -O2 -D_FORTIFY_SOURCE=2 through CFLAGS will conflict with the module's level 3: the module's -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3 come later on the command line for the target, so level 3 wins, though that depends on the order CMake emits flags. If you want the distribution's choice to prevail, guard the fortify lines with if(NOT DEFINED ENV{CFLAGS}).
Verify the result in the build
A configure-time check does not prove the output. Add a post-build step that runs the checks from the earlier posts on the real executable. A small script, cmake/verify-elf.sh, can call readelf and fail on a missing property, and CMake runs it after the link:
add_custom_command(TARGET demo POST_BUILD
COMMAND ${CMAKE_SOURCE_DIR}/cmake/verify-elf.sh $<TARGET_FILE:demo>
COMMENT "Checking hardening of demo")The next post in this series builds that script. Without it, run readelf -h, readelf -lW and readelf -d by hand on a release build and confirm DYN, GNU_STACK ... RW, GNU_RELRO and BIND_NOW.
Common problems
A flag is missing in the build. Look at
compile_commands.jsonorcmake --build -v. The usual causes are a target that never calledharden_target, a subproject with its own flags andCMAKE_C_FLAGSset after the target was created, which does not affect it.**
-Wl,-z,nowslows startup noticeably.** The cost is paid once for all imports, and the earlier post on RELRO says how to measure it.**Clang and
-fstack-clash-protection.** Clang supports it from version 11 on Linux x86-64 and AArch64, so the check passes there, and the flag is accepted as a no-op on targets that do not need it.Cross builds.
check_compiler_flagruns the compiler for the target, so flags are tested correctly, buttry_runchecks do not work when cross-compiling. This module uses only compile and link tests.C++ projects. Repeat the checks with
CXX, and add_GLIBCXX_ASSERTIONSor the libc++ hardening macro from the C++ post in this series.
Presets and toolchain files
Teams that build with many configurations often keep their flags in CMakePresets.json or a toolchain file instead of a module. That works for the flags that apply to every target, such as CMAKE_EXE_LINKER_FLAGS_INIT with -Wl,-z,relro,-z,now, and it has the weaknesses of any global setting: it covers only what is built with that preset, and a downstream user who builds with their own flags bypasses it. A good arrangement uses both. The module applies the flags per target so they travel with the code, and a CI preset sets the build type to Release and turns on -Werror so that a warning from a new flag fails the job. If you export your targets for others to link against, remember that PRIVATE options do not propagate, which is what you want for hardening flags, since the consumer's build should decide its own.
A separate concern is code you do not compile yourself. A prebuilt static library or a binary dependency carries the flags of whoever built it, and no CMake option can change that. Record those in the project's notes, run the verification script on the final executable and ask the vendor for hardened builds when a check fails.


