What are the useful GCC flags for C?

Viewed 74515

Beyond setting -Wall, and setting -std=XXX, what other really useful, but less known compiler flags are there for use in C?

I'm particularly interested in any additional warnings, and/or and turning warnings into errors in some cases to absolutely minimize any accidental type mismatches.

24 Answers
  • -Wmissing-prototypes: If a global function is defined without a previous prototype declaration.
  • -Wformat-security: Warns about uses of format functions that represent possible security problems. At present, this warns about calls to printf and scanf functions where the format string is not a string literal and there are no format arguments
  • -Werror=return-type: Enforce error when function has no return in gcc. It is /we4716 in Visual Studio.

  • -Werror=implicit-function-declaration: Enforce error when function is used without defined / not included. It is /we4013 in Visual Studio.

  • -Werror=incompatible-pointer-types: Enfore error when a pointer's type mismatched with expected pointer type. It is /we4133 in Visual Studio.

Actually, I'd like to keep my C code cross-platform, and I use CMake, and I put the provided cflags into CMakeLists.txt like:

if (CMAKE_SYSTEM_NAME MATCHES "Windows")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /we4013 /we4133 /we4716")
elseif (CMAKE_SYSTEM_NAME MATCHES "Linux" OR CMAKE_SYSTEM_NAME MATCHES "Darwin")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror=implicit-function-declaration -Werror=incompatible-pointer-types -Werror=return-type")
endif()
Related