Here are mine:

  • -Wextra and -Wall: essential.
  • -Wfloat-equal: useful because usually testing floating-point numbers for equality is bad.
  • -Wundef: warn if an uninitialized identifier is evaluated in an #if directive.
  • -Wshadow: warn whenever a local variable shadows another local variable, parameter or global variable or whenever a built-in function is shadowed.
  • -Wpointer-arith: warn if anything depends upon the size of a function or of void.
  • -Wcast-align: warn whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a char * is cast to an int * on machines where integers can only be accessed at two- or four-byte boundaries.
  • -Wstrict-prototypes: warn if a function is declared or defined without specifying the argument types.
  • -Wstrict-overflow=5: warns about cases where the compiler optimizes based on the assumption that signed overflow does not occur. (The value 5 may be too strict, see the manual page.)
  • -Wwrite-strings: give string constants the type const char[length] so that copying the address of one into a non-const char * pointer will get a warning.
  • -Waggregate-return: warn if any functions that return structures or unions are defined or called.
  • -Wcast-qual: warn whenever a pointer is cast to remove a type qualifier from the target type*.
  • -Wswitch-default: warn whenever a switch statement does not have a default case*.
  • -Wswitch-enum: warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration*.
  • -Wconversion: warn for implicit conversions that may alter a value*.
  • -Wunreachable-code: warn if the compiler detects that code will never be executed*.

Those marked * sometimes give too many spurious warnings, so I use them on as-needed basis.

Answer from Alok Singhal on Stack Overflow
🌐
Bookmarklet Maker
caiorss.github.io › C-Cpp-Notes › compiler-flags-options.html
CPP/C++ Compiler Flags and Options
=> Add search path to shared libraries, directory containing *.so, *.dll or *.dlyb files such as libLinearAlgebra.so depending on the current operating system. ... Add search path to header files (.h) or (.hpp). ... Turns on lots of compiler warning flags, specifically (-Waddress, -Wcomment, -Wformat, -Wbool-compare, -Wuninitialized, -Wunknown-pragmas, -Wunused-value, -Wunused-value …)
🌐
Red Hat
developers.redhat.com › blog › 2018 › 03 › 21 › compiler-and-linker-flags-gcc
Recommended compiler and linker flags for GCC | Red Hat Developer
July 2, 2024 - Did you know that when you compile your C or C++ programs, the GCC compiler will not enable all exceptions by default? Do you know which build flags you need to specify in order to obtain the same level of security hardening that GNU/Linux distributions use (such as Red Hat Enterprise Linux and Fedora)? This article walks through a list of recommended build flags.
Top answer
1 of 16
178

Here are mine:

  • -Wextra and -Wall: essential.
  • -Wfloat-equal: useful because usually testing floating-point numbers for equality is bad.
  • -Wundef: warn if an uninitialized identifier is evaluated in an #if directive.
  • -Wshadow: warn whenever a local variable shadows another local variable, parameter or global variable or whenever a built-in function is shadowed.
  • -Wpointer-arith: warn if anything depends upon the size of a function or of void.
  • -Wcast-align: warn whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a char * is cast to an int * on machines where integers can only be accessed at two- or four-byte boundaries.
  • -Wstrict-prototypes: warn if a function is declared or defined without specifying the argument types.
  • -Wstrict-overflow=5: warns about cases where the compiler optimizes based on the assumption that signed overflow does not occur. (The value 5 may be too strict, see the manual page.)
  • -Wwrite-strings: give string constants the type const char[length] so that copying the address of one into a non-const char * pointer will get a warning.
  • -Waggregate-return: warn if any functions that return structures or unions are defined or called.
  • -Wcast-qual: warn whenever a pointer is cast to remove a type qualifier from the target type*.
  • -Wswitch-default: warn whenever a switch statement does not have a default case*.
  • -Wswitch-enum: warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration*.
  • -Wconversion: warn for implicit conversions that may alter a value*.
  • -Wunreachable-code: warn if the compiler detects that code will never be executed*.

Those marked * sometimes give too many spurious warnings, so I use them on as-needed basis.

2 of 16
77

Several of the -f code generation options are interesting:

  • -fverbose-asm is useful if you're compiling with -S to examine the assembly output - it adds some informative comments.

  • -finstrument-functions adds code to call user-supplied profiling functions at every function entry and exit point.

  • --coverage instruments the branches and calls in the program and creates a coverage notes file, so that when the program is run coverage data is produced that can be formatted by the gcov program to help analysing test coverage.

  • -fsanitize={address,thread,undefined} enables the AddressSanitizer, ThreadSanitizer and UndefinedBehaviorSanitizer code sanitizers, respectively. These instrument the program to check for various sorts of errors at runtime.

Previously this answer also mentioned -ftrapv, however this functionality has been superseded by -fsanitize=signed-integer-overflow which is one of the sanitizers enabled by -fsanitize=undefined.

🌐
Nullprogram
nullprogram.com › blog › 2023 › 04 › 29
My favorite C compiler flags during development
The major compilers have an enormous number of knobs. Most are highly specialized, but others are generally useful even if uncommon. For warnings, the venerable -Wall -Wextra is a good start, but circumstances improve by tweaking this warning set.
🌐
Reddit
reddit.com › r/c_programming › [u/skeeto's blog] "my favorite c compiler flags during development"
r/C_Programming on Reddit: [u/skeeto's blog] "My favorite C compiler flags during development"
April 30, 2023 - My software rasterizer was riddled with memory issues and undefined behavior that I thought I had been clever enough to avoid, and without these dynamic check tools I shudder to think of all the crashes and weird quirks in my program that I'd still just be guessing about. ... In addition to the warning options listed in the article, the following are highly beneficial and are not part of -Wall or -Wextra: -Wnull-dereference: Warn if the compiler detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer.
🌐
Oracle
docs.oracle.com › cd › E19957-01 › 806-3567 › cc_options.html
cc Compiler Options
Retains temporary files created during compilation instead of deleting them automatically. ... dir to the list of directories searched for libraries by ld(1). This option and its arguments are passed to ld. ... name.a. The order of libraries in the command-line is important, as symbols are resolved from left to right. ... Removes duplicate strings from the .comment section of the object file. When you use the -mc flag, mcs -c is invoked.
🌐
Openssf
best.openssf.org › Compiler-Hardening-Guides › Compiler-Options-Hardening-Guide-for-C-and-C++.html
Compiler Options Hardening Guide for C and C++ | OpenSSF Best Practices Working Group
Similarly, running cc -O2 -dM -E - < /dev/null will produce a comprehensive list of macro-defined constants. This output can be useful for troubleshooting problems related to compiler or library features that are enabled through specific macro definitions. It’s important to note that sourcing GCC from third-party vendor may result in your instance of GCC being preconfigured with certain default flags enabled or disabled.
🌐
Medium
medium.com › @promisevector › c-programming-mastering-flags-in-gcc-32809491f340
C Programming: Mastering Flags in GCC | by Chizaram Nwachukwu | Medium
July 2, 2023 - So far, we’ve been introduced to the C programming language and the GCC, which is our go-to compiler for the C programming language. In today’s episode, we will identify all the commonly used flags in the GCC compilation process and what they do to our C code scripts.
Find elsewhere
🌐
IBM
ibm.com › docs › en › xl-c-and-cpp-aix › 16.1.0
XL C/C++ for AIX
We cannot provide a description for this page right now
🌐
Umu
hpc2n.umu.se › documentation › compilers › flags
Compiler Flags | www.hpc2n.umu.se
This page contains information about some of the more important/popular flags for the compilers available at HPC2N. The flags below can all be taken to be valid for the Fortran and C/C++ compilers alike, as well as for compiling with the MPI libraries included (remember to load the proper modules ...
🌐
Reddit
reddit.com › r/cpp › compiler flags
r/cpp on Reddit: Compiler flags
August 25, 2024 -

Recently had a discussion with someone regarding compile flags and their function.

While I like enabling as many warnings as possible (and fixing them) to prevent nasty bugs, the other rather not enable them.

Currently in my debug build it's -Wall -Wextra -Wpedantic -Wreorder -Wunused -Wshadow -Werror=return-type

Some warnings are obviously more useful than others. -Wunused just warns about unused parameters or variables. I don't think that's really critical, but it just keeps my code clean.

-Wreorder gives a warning if initialisation order is different than parameter order. Also, don't think it's that critical (please tell me I'm wrong of it is). This might be more useful to keep some sort of standard in initialisation when you are with more people on a project?

I am wondering: what flags do you use on debug / release builds? Did you ever encounter nasty bugs that could have been prevented with some specific flags?

🌐
CMake
cmake.org › cmake › help › latest › module › CheckCCompilerFlag.html
CheckCCompilerFlag — CMake 4.3.0-rc1 Documentation
Since the underlying try_compile() command also uses flags from variables like CMAKE_<LANG>_FLAGS, unknown or unsupported flags in those variables may result in a false negative for this check. ... A space-separated string of additional flags to pass to the compiler. A semicolon-separated list will ...
🌐
Cam
wikis.ch.cam.ac.uk › ro-walesdocs › wiki › index.php › Compiler_Flags
Compiler Flags - Docswiki
-ftrapv The compiler creates a runtime trap when a variable overflow occurs. -fimplicit-none No implicit typing is allowed, unless there is an explicit IMPLICIT statement. This is equivalent to putting IMPLICIT NONE everywhere there isn't already an IMPLICIT statement. All: -Mextend -mcmodel=medium (only for NEWREAXFFOPTIM) ... -mcmodel=medium This is only when building with NEWREAXFFOPTIM. The flag must be used to compile/link a program whose data and .bss sections exceed 2GB.
🌐
Linux Handbook
linuxhandbook.com › gcc-flags
Important GCC Flags in Linux
December 16, 2022 - To link the C program with a shared library, all you have to do is append the name of the shared library with the -l flag · For example, here I have linked the code main.c with the shared library pthread to produce the final executable Result: ... But what if you want to link the external libraries? In that case, you'd have to specify the location of the external library using the -L. For example, here, I have linked the shared library “LHB” stored in /home/user/LHB: ... The pre-processing is the first stage of compilation and if you are only concerned with what happens to your code in the first stage, you can use the -E flag.
🌐
Quora
quora.com › What-are-the-important-recommended-GCC-compiler-flags-to-use-when-learning-C
What are the important/recommended GCC compiler flags to use when learning C++? - Quora
Answer (1 of 6): My preferred options would be -Werror, -Wall, -Wextra, -pedantic, and the -std flag for the latest version of the language available with your compiler. On current compilers it would be -std=c++17.
🌐
Boston University
bu.edu › tech › support › research › software-and-programming › programming › compilers › gcc-compiler-flags
GNU and LLVM Compiler Flags : TechWeb : Boston University
Codes compiled with -march=native on a login node will only be able to execute on Broadwell architecture compute nodes on the SCC. Most codes will be well-optimized with the -O2 or -O3 flags plus the -msse4.2 flag. Programs that involve intensive floating-point calculations inside of loops can additionally be compiled with the -xarch flag.
🌐
O'Reilly
oreilly.com › library › view › objective-c-pocket-reference › 0596004230 › ch01s05.html
1.5. Compiler Flags - Objective-C Pocket Reference [Book]
December 19, 2002 - 1.12.1. Manual Memory Management1.12.2. Reference Counting1.12.2.1. Maintaining an object’s reference count1.12.2.2. Creating a new object1.12.2.3. Receiving an object from another scope1.12.2.4. Returning an already-stored object1.12.2.5. Replacing an already-stored object1.12.2.6. Deallocating an object1.12.2.7. Retain cycles1.12.3. Garbage Collection · 1.13.1. Archiving Descendants of Object1.13.2. Archiving Descendants of NSObject · 1.14.1. Access Permissions1.14.2. NSKeyValueCoding Methods1.14.3. Handling Key Lookup Failures ... Compiler flags are options you give to gcc when it compiles a file or set of files.
Author   Andrew Duncan
Published   2002
Pages   128
🌐
Reddit
reddit.com › r/c_programming › gcc flags
r/C_Programming on Reddit: GCC flags
November 18, 2023 -

Hi,

I'm a beginner, barely scratching the surface of C at the moment. Question is, what flags do I choose for compilation? There are some "basic" like -Wall, -W, -pedantic, -ansi, -std=. GCC documentation has a ton of different flags.
Should I learn Make or CMake early to avoid retyping flags every time to compile my source files?Any help, advice are greatly appreciated.
Edit: thank you, guys. Lots of useful and interesting information. You're awesome!

Top answer
1 of 5
13
I'd recommend what you have plus Wextra. As for the second question, simply alias a build command. alias gcc_test='gcc -Wall -Wextra -pedantic -std=c99' Obviously, replace gcc_test with whatever you will remember! Then you can use gcc_test -o myprogram myprogram.c
2 of 5
4
For warnings, start with -Wall -Wextra. Everybody has a different set of flags they like on top of these. You don’t need to get everything now, just start with those two. For standard, start with -std=c11 or -std=c17. Or -std=gnu11 or -std=gnu17. The exact standard is not a big deal. Just pick one, because if you don’t pick one, you’ll get some default and you won’t know which one you’re using. Add -g so you can use the debugger. Add -fsanitize=address when you need help finding memory errors. Avoid using -pedantic. It’s not really that helpful. It just kinda gets in the way. Should I learn Make or CMake early to avoid retyping flags every time to compile my source files? My first recommendation is to use a good build system like Meson, or an IDE like Visual Studio, Code::Blocks, or Xcode. You can use CMake instead, but it kinda sucks. You can use Make, but it sucks a lot. Maybe you like these better. There are a lot of reasons why Make sucks, so I don’t recommend it to anyone. Even if you don’t use one of those build systems, you can at least write a shell script to compile everything. Paste your command line into a text file and then chmod +x that text file, so you can run it to build. For example, you could have a text file named build which looks like this: gcc -Wall -Wextra -g -std=c17 main.c lib.c Then you chmod it +x: $ chmod +x build Then you can run it: $ ./build