Skip to content

Commit 1e8c32e

Browse files
committed
Add compiler-specific hardening flags for MSVC
1 parent 015e190 commit 1e8c32e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

CMakeLists.txt

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,45 @@ if(CMAKE_CXX_COMPILER_ID MATCHES "^(Clang|GNU)$")
146146
# Mark Global Offset Table read-only after resolving symbols.
147147
-Wl,-z,relro
148148
)
149+
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
150+
add_compile_options(
151+
# Enable compiler warnings.
152+
# https://docs.microsoft.com/en-us/cpp/build/reference/compiler-option-warning-level
153+
/Wall
154+
# Enable buffer security check.
155+
# https://docs.microsoft.com/en-us/cpp/build/reference/gs-buffer-security-check
156+
/GS
157+
# Enable additional security shecks.
158+
# https://docs.microsoft.com/en-us/cpp/build/reference/sdl-enable-additional-security-checks
159+
/sdl
160+
# Disable warnings about the use of safe C library functions, which
161+
# suggest the use of proprietary, non-portable alternatives.
162+
# https://gitlab.gnome.org/GNOME/glib/-/issues/2357
163+
# https://github.com/GNOME/glib/blob/49ec7f18e3fd1070a8d546ae6cc4acbea8055dbc/msvc_recommended_pragmas.h#L39-L41
164+
-D_CRT_SECURE_NO_WARNINGS
165+
-D_CRT_NONSTDC_NO_WARNINGS
166+
)
167+
168+
# We need to support CMake 3.10, add_link_options() was added in CMake 3.13.
169+
# link_libraries() passes flags through as long as they do not contain spaces.
170+
# https://cmake.org/cmake/help/v3.13/command/add_link_options.html
171+
link_libraries(
172+
# Enable address space layout randomization.
173+
# https://docs.microsoft.com/en-us/cpp/build/reference/dynamicbase-use-address-space-layout-randomization
174+
-DYNAMICBASE
175+
# Always generate relocation section.
176+
# https://docs.microsoft.com/en-us/cpp/build/reference/fixed-fixed-base-address
177+
-FIXED:NO
178+
# Disable unneeded incremental linking for better performance and smaller size.
179+
# https://docs.microsoft.com/en-us/cpp/build/reference/incremental-link-incrementally
180+
-INCREMENTAL:NO
181+
# Enable compatibility with data execution prevention.
182+
# https://docs.microsoft.com/en-us/cpp/build/reference/nxcompat-compatible-with-data-execution-prevention
183+
-NXCOMPAT
184+
# Keep unreferenced symbols.
185+
# https://docs.microsoft.com/en-us/cpp/build/reference/opt-optimizations
186+
-OPT:NOREF
187+
)
149188
endif()
150189

151190
# https://clang.llvm.org/docs/AddressSanitizer.html

0 commit comments

Comments
 (0)