Enable Compiler Warnings using CMake

Enable Compiler Warnings using CMake

Compiler warnings help developers write cleaner, safer, and more maintainable code. They help catch potential bugs early, enforce good practices, and improve code quality. But unless explicitly enabled, many compilers won't show all useful warnings by default. This tutorial explains how to enable compiler warnings using CMake.

Enable compiler warnings

To enable compiler warnings, we can use the following CMake script:

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

add_executable(${PROJECT_NAME} main.cpp)

if (MSVC)
    target_compile_options(${PROJECT_NAME} PRIVATE /W4)
else ()
    target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Wpedantic)
endif ()

The script includes a conditional statement: if the compiler is Microsoft Visual C++ (MSVC), it adds the /W4 option; otherwise, it adds the -Wall -Wextra -Wpedantic options for GCC or Clang.

Explanation of compiler flags:

  • /W4 - sets the warning level to 4, which is the second-highest level in MSVC. It includes a wide range of potentially useful warnings without being overly verbose. You can go up to /Wall, but that often includes noisy, low-value warnings.
  • -Wall - enables a broad set of commonly useful warnings.
  • -Wextra - adds even more, such as unused parameter warnings.
  • -Wpedantic - ensures strict compliance with the language standard and warns things that may be technically allowed by the compiler but not by the standard.

Treat warnings as errors

Once you've enabled warnings and addressed the existing ones, you can take things a step further by treating warnings as build-breaking errors. This approach forces developers to resolve warnings immediately instead of letting them pile up over time.

if (MSVC)
    target_compile_options(${PROJECT_NAME} PRIVATE /W4 /WX)
else ()
    target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Wpedantic -Werror)
endif ()

The /WX or -Werror flag will treat warnings as errors, meaning the build will fail if any warning is triggered.

Leave a Comment

Cancel reply

Your email address will not be published.