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
🌐
Linux Handbook
linuxhandbook.com › gcc-flags
Important GCC Flags in Linux
December 16, 2022 - In the most basic term, you will use the GCC compiler as follows: ... And the above command will compile the program and it will create an executable with the name a.out.: To specify the output executable filename, all you need to do is append the filename with the -o flag as shown below: ... If you want to print every warning so that you can examine your code and make it better than ever, use the -Wall flag.
🌐
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 - During the build process to create distributions such as Fedora and Red Hat Enterprise Linux, compiler and linker flags have to be injected, as discussed below. When you are using one of these distributions with the included compiler, this environment is recreated, requiring an extensive list of flags to be specified. Recommended flags vary between distribution versions because of toolchain and kernel limitations. The following table lists recommended build flags (as seen by the gcc and g++ compiler drivers), along with a brief description of which version of Red Hat Enterprise Linux and Fedora are applicable.
🌐
Linux Questions
linuxquestions.org › questions › linux-software-2 › gcc-flags-553790
GCC Flags
I am reading a book called setting up LAMP and there is a section which teaches how to install mysql from source. The source files are to be compiled,
🌐
Linux Man Pages
man7.org › linux › man-pages › man1 › gcc.1.html
gcc(1) - Linux manual page
When you invoke GCC, it normally does preprocessing, compilation, assembly and linking. The "overall options" allow you to stop this process at an intermediate stage. For example, the -c option says not to run the linker. Then the output consists of object files output by the assembler.
🌐
GNU
gcc.gnu.org › onlinedocs › gcc › Option-Summary.html
Option Summary (Using the GNU Compiler Collection (GCC))
-fcall-saved-reg -fcall-used-reg -ffixed-reg -fexceptions -fnon-call-exceptions -fdelete-dead-exceptions -funwind-tables -fasynchronous-unwind-tables -fno-gnu-unique -finhibit-size-directive -fcommon -fno-ident -fpcc-struct-return -fpic -fPIC -fpie -fPIE -fno-plt -fno-jump-tables -fno-bit-tests -frecord-gcc-switches -freg-struct-return -fshort-enums -fshort-wchar -fverbose-asm -fpack-struct[=n] -fleading-underscore -ftls-model=model -fstack-reuse=reuse_level -ftrampolines -ftrampoline-impl=[stack|heap] -ftrapv -fwrapv -fwrapv-pointer -fvisibility=[default|internal|hidden|protected] -fstrict-volatile-bitfields -fsync-libcalls -fzero-init-padding-bits=value -Qy -Qn
🌐
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
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.

🌐
Bookmarklet Maker
caiorss.github.io › C-Cpp-Notes › compiler-flags-options.html
CPP/C++ Compiler Flags and Options
Shows many GCC optimization options. ... Reports bugs that the optimization –fast-math may cause. ... Performance Optimization Getting your programs to run faster CS 691. ... https://www.slideshare.net/MarinaKolpakova/pragmatic-optimization-in-modern-programming-mastering-compiler-optimizations · Note: Those switches/flags are also useful for embedded systems. The Undefined Behavior Sanitizer - UBSAN — The Linux Kernel documentation
Find elsewhere
🌐
RapidTables
rapidtables.com › code › linux › gcc › gcc-o.html
gcc -o / -O option flags (output / optimization)
Home›Code›Linux›GCC› gcc -o / -O · gcc -o writes the build output to an output file. gcc -O sets the compiler's optimization level. gcc -o option flag · gcc -O option flag · Write the build output to an output file. $ gcc [options] [source files] [object files] -o output file ·
🌐
Arch Linux Forums
bbs.archlinux.org › viewtopic.php
Get gcc to show all the CFLAGS including those auto set? [SOLVED] / Programming & Scripting / Arch Linux Forums
So -v would do that, at least by ... from the gcc PKGBUILD itself... but that would take some parsing. It does also show you the resolved FLAGS for -march=native so that's good. Again, that is rather more verbose than most people will want and anyways this is probably best picked up from the environment CFLAGS rather than the project Makefile. As for inspecting the contents of a binary, we (Arch Linux) want that ...
🌐
LinuxForDevices
linuxfordevices.com › home › top 10 important gcc flags for linux geeks
Top 10 Important GCC Flags For Linux Geeks - LinuxForDevices
April 25, 2021 - For example you have all the flags you want to be included during compilation like : ... This can come in handy when you want to make sure that all your executables have some common standards or to save the pain of typing the same long list of files over and over again. Thus in this module we saw some of the useful GCC flags.
🌐
GNU
gcc.gnu.org › onlinedocs › gccint › Flags.html
Flags (GNU Compiler Collection (GCC) Internals)
Nonzero in an insn, call_insn, jump_insn, barrier, or set which is part of a function prologue and sets the stack pointer, sets the frame pointer, or saves a register. This flag should also be set on an instruction that sets up a temporary register to use in place of the frame pointer.
🌐
Stanford
web.stanford.edu › class › archive › cs › cs107 › cs107.1186 › unixref › topics › gcc
gcc (how to compile c programs)
gcc takes many different command line options (flags) that change its behavior. One of the most common flags is the "optimization level" flag, -O (uppercase 'o'). gcc has the ability to optimize your code for various situations.
🌐
SPEC
spec.org › cpu2017 › flags › gcc.html
GNU Compiler Collection Flags
There are a group of GCC optimizations invoked via -ftree-vectorize and related flags, as described at https://gcc.gnu.org/projects/tree-ssa/vectorization.html. During testing of SPEC CPU2017, for some versions of GCC on some chips, some benchmarks did not get correct answers when the vectorizor was enabled.
🌐
Httrack
blog.httrack.com › blog › 2014 › 03 › 09 › what-are-your-gcc-flags
What Are Your GCC Flags ? - xavier roche's homework
gcc -pipe -m64 -ansi -fPIC -g -O3 -fno-exceptions -fstack-protector -Wl,-z,relro -Wl,-z,now -fvisibility=hidden -W -Wall -Wno-unused-parameter -Wno-unused-function -Wno-unused-label -Wpointer-arith -Wformat -Wreturn-type -Wsign-compare -Wmultichar -Wformat-nonliteral -Winit-self -Wuninitialized -Wno-deprecated -Wformat-security -Werror -c source.c -o dest.o · Within these fancy flags, I was among the craziest tuner.
🌐
EndeavourOS
forum.endeavouros.com › lounge
GCC - How to figure out what default flags it is using - Lounge - EndeavourOS
February 22, 2020 - With the GCC compiler, how do I figure out what default flags is it using?
Top answer
1 of 2
1

You don't need any environment variables, just pass in right cflags and ldflags that SDL2 wants you to use:

gcc main.c `pkg-config --cflags sdl2` -o main `pkg-config --libs sdl2`

or either

gcc main.c `sdl2-config --cflags` -o main `sdl2-config --libs`

Remember: CFLAGS come before LDFLAGS, and LDFLAGS (and library specification with -l) comes last.

SDL2 comes with sdl2-config script preinstalled. You will need to set your PATH to the directory where it resides to call it successfully:

export PATH=/opt/SDL2/bin:$PATH

If you will run every of *-config commands directly, you will see that they just output right cflags and ldflags for you. That's because the libraries that employ these scripts usually bigger than to specify single -I/-L argument, and it is not portable to specify single -I/-L arguments for them, because number of such arguments can be increased in future.

And you should not install every package in it's own directory. Install everything into /usr/local for example, then you will not need even to specify anything (most distros point you to /usr/local automatically).

2 of 2
1

As can be seen in the Catalogue of Built-In Rules:

Linking a single object file

n is made automatically from n.o by running the linker (usually called ld) via the C compiler. The precise recipe used is:

$(CC) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS)

and Variables Used by Implicit Rules:

LDFLAGS

Extra flags to give to compilers when they are supposed to invoke the linker, ld, such as -L. Libraries (-lfoo) should be added to the LDLIBS variable instead.

So in this case -lSDL2 should be set or added to LDLIBS, not LDFLAGS.

🌐
Gentoo Wiki
wiki.gentoo.org › wiki › GCC_optimization › en
GCC optimization - Gentoo wiki
CPU_FLAGS_* — a USE_EXPAND variable containing instruction set and other CPU-specific features. Safe CFLAGS — a summary of "safe" settings for CFLAGS on Gentoo Linux. ... ↑ GNU GCC Bugzilla, AVX/AVX2 no ymm registers used in a trivial reduction.
🌐
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
This section describes recommendations for compiler and linker option flags that 1) enable compile-time checks that warn developers of potential defects in the source code (Table 1), and 2) enable run-time protection mechanisms, such as checks that are designed to detect when memory vulnerabilities ...