Table of Contents
GCC Warnings
Compiler warnings catch bugs at compile time—uninitialized variables, type mismatches, unused code, unreachable statements. Treating warnings as bugs forces you to write cleaner code.
gcc -Wall -Wextra -Wpedantic -o app app.c
-Wall enables a curated set of common warnings (despite the name, it's not “all warnings”). -Wextra adds additional checks. -Wpedantic flags non-standard GNU extensions, useful for portability.
Common warnings:
-Wuninitialized uninitialized variable usage -Wshadow variable shadows an outer scope variable -Wunused-variable declared but never used -Wunused-result result of function call discarded -Wtype-limits comparison always true/false (logic error) -Wstrict-overflow signed integer overflow (undefined behavior) -Wformat printf format string mismatches
Treating warnings as errors:
gcc -Wall -Wextra -Werror -o app app.c
-Werror converts warnings to errors, halting compilation. Forces you to fix issues immediately. Recommended for production builds and CI/CD.
Selectively disabling warnings:
#pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" int unused_var = 0; #pragma GCC diagnostic pop
Use when a warning is a false positive or unfixable in legacy code. Document the reason.
Compiler-specific warnings: Different compilers (GCC, Clang) have different warnings. For maximum portability:
gcc -Wall -Wextra -Wpedantic clang -Wall -Wextra -Wpedantic -Weverything # Clang is stricter
Clang has more warnings by default. Code that compiles cleanly with both is more portable.
Example catch: Uninitialized variable:
int x; // uninitialized printf("%d", x); // -Wuninitialized warns about this
Without warnings, this is undefined behavior—the program reads garbage. With warnings, the compiler catches it immediately.
Build setup: Add warnings to your Makefile or build system:
CFLAGS = -Wall -Wextra -Wpedantic -Werror -O3 -g
This ensures every compilation runs with consistent warning levels. Over time, you'll fix issues and the codebase becomes cleaner.
