Skip to content
systemcoding.dev
Fundamentals

Turn on -Wall -Wextra -Wpedantic to catch UB-adjacent bugs

Compile C with -Wall -Wextra -Wpedantic so GCC 14 flags an assignment in a condition and a signed/unsigned compare before they become silent bugs.

2 min read
Summarize in AI

GCC and Clang accept a lot of dubious C without a word. Three flags change that: -Wall for the common mistakes, -Wextra for a second tier, and -Wpedantic for anything outside the ISO standard, such as compiler extensions you did not mean to use. None of them changes the generated code; they only make the compiler talk.

warn.cc
#include <stdio.h>

int main(void) {
    int i = -1;
    unsigned u = 1;
    int x = 0;

    if (x = 1)
        puts("assigned");
    if (i < u)
        puts("-1 is less than 1");
    return 0;
}
Text
warn.c: In function 'main':
warn.c:8:11: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
    8 |     if (x = 1)
      |         ~~^~~
warn.c:10:11: warning: comparison of integer expressions of different signedness: 'int' and 'unsigned int' [-Wsign-compare]
   10 |     if (i < u)
      |           ^

Build it with gcc -std=c17 -Wall -Wextra -Wpedantic warn.c. The first warning is = where == was meant, which compiles and always takes the branch. The second is the quieter one: i is converted to unsigned, becomes 4294967295, and the comparison is false, so the second line never prints. In C, -Wsign-compare comes from -Wextra, not -Wall, which is why -Wall alone is not enough.

These warnings find code that is correct on one compiler and wrong on another. They do not find real undefined behaviour in general; that needs the sanitizers. Options are listed in the GCC warning options manual. Add -Werror in CI, not on a developer's default build, so a new compiler's extra warnings do not stop a release.

Taggedcgcc
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.