Community practices for platform/compiler specific compiler options

I would like to build my project under Windows using Visual Studio 2022, and under Linux using Clang and Gcc. For each case, I have a set of options that I would like to apply to the entire project. I would like to know the community practices for achieving this.

I decided to kick start this discussion by sharing what I personally decided to do. This is my project structrue:

Project Root
|
---- cmake [dir]
     |
     ---- clang_config.cmake
     ---- gcc_config.cmake
     ---- msvc_config.cmake
---- CMakeLists.txt

In the root CMakeLisrts.txt, I include the cmake directory in the search path for modules and include all the modules:

set(CMAKE_MODULE_PATH
“${CMAKE_CURRENT_SOURCE_DIR}/cmake”
)

include(“clang_config”)
include(“gcc_config”)
include(“msvc_config”)

These modules are responsible for creating the variables

_COMPILE_DEFINITIONS, e.g., MSVC_COMPILE_DEFINITIONS
_COMPILE_OPTIONS, e.g., MSVC_COMPILE_OPTIONS
_LINK_OPTIONS, e.g., MSVC_LINK_OPTIONS

And then I use them as follows:

add_compile_definitions(
“$<$<CXX_COMPILER_ID:Clang>:${CLANG_COMPILE_DEFINITIONS}>”
“$<$<CXX_COMPILER_ID:GNU>:${GCC_COMPILE_DEFINITIONS}>”
“$<$<CXX_COMPILER_ID:MSVC>:${MSVC_COMPILE_DEFINITIONS}>”
)

add_compile_options(
“$<$<CXX_COMPILER_ID:Clang>:${CLANG_COMPILE_OPTIONS}>”
“$<$<CXX_COMPILER_ID:GNU>:${GCC_COMPILE_OPTIONS}>”
“$<$<CXX_COMPILER_ID:MSVC>:${MSVC_COMPILE_OPTIONS}>”
)

add_link_options(
“$<$<CXX_COMPILER_ID:Clang>:${CLANG_LINK_OPTIONS}>”
“$<$<CXX_COMPILER_ID:GNU>:${GCC_LINK_OPTIONS}>”
“$<$<CXX_COMPILER_ID:MSVC>:${MSVC_LINK_OPTIONS}>”
)

An example of how the MSVC module could create the MSVC_COMPILE_OPTIONS variable is as follows.

#NOTE The forum software is NOT allowing me to add the forward slashes to the options below because it interprets them as links, and new users are only allowed two links in their posts.

Generic options for all configurations

list(APPEND
MSVC_COMPILE_OPTIONS
permissive-
Wall
WX
)

Debug options

list(APPEND
MSVC_COMPILE_DEBUG_OPTIONS
fsanitize=address
fsanitize=fuzzer
)
list(APPEND
MSVC_COMPILE_OPTIONS
$<$CONFIG:Debug:${MSVC_COMPILE_DEBUG_OPTIONS}>
)

Release options

list(APPEND
MSVC_COMPILE_RELEASE_OPTIONS
O2
Oi
Ot
Oy
)
list(APPEND
MSVC_COMPILE_OPTIONS
$<$CONFIG:Release:${MSVC_COMPILE_RELEASE_OPTIONS}>
)

RelWithDebInfo options

list(APPEND
MSVC_COMPILE_REL_WITH_DEB_INFO_OPTIONS
${MSVC_COMPILE_RELEASE_OPTIONS}
JMC
Zi
Zo
)
list(APPEND
MSVC_COMPILE_OPTIONS
$<$CONFIG:RelWithDebInfo:${MSVC_COMPILE_REL_WITH_DEB_INFO_OPTIONS}>
)