Skip to content

Commit 521f78f

Browse files
committed
Add compiler-specific hardening flags for MSVC
1 parent 7078b1a commit 521f78f

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

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

0 commit comments

Comments
 (0)