Cover image for 10 Useful GCC Flags That I Use Regularly

10 Useful GCC Flags That I Use Regularly

mithil467 profile image Mithil Poojary ・2 min read

C++ was my first programming language. I have been learning and using it for a little less than 2 years now. I have been of the idealogy (which is silly) that if something can be done in c++, do it in c++. Yes, I am slowly moving towards other feasible solutions for certain use cases.
Here are my frequently used gcc flags.

1. -o

gcc example.c -o outfile

The default executable name is a.exe or a.out or something similar depending on the host machine. You can easily set the executable name to, for example, outfile in this case. Other file names are also affected, like object files, assembler files.

2. -Wall, -Wextra

Wall and Wextra turn on certain warning flags, that are almost certainly errors in my experience.

3. -O2

gcc optimizes code for compilation speeds by default. You can enable this flag and optimize the code for runtime. The compiler optimization step is crazy and can optimize the code to extents one cannot imagine! I have read somewhere the compiler optimized a for loop which was adding some element each iteration to a single multiplication statement!

4. -g

Produces debugging information. Helpful when debugging with gdb as variable names, function names are listed which otherwise are not.

5. -S

Your C source code is compiled down to assembly first. The assembly output is stored in a file with the help of the -S flag.

6. -E

Do preprocessing only, and output the entire source code. You include a lot of headers inside your code, all that does is copying the content of the header into the source. This outputs the preprocessed source code.

7. -Wfloat-equal

Directly comparing floats is a bad idea. If you execute:

float a=0.2f, b=0.2f;
if(a + b != 0.4)
printf("Not equal");

You will get the output Not equal. This is because of precision issues. This can be caught by the compiler by using -Wfloat-equal flag. I will soon write a post explaining this behavior, and how to tackle it. For now, just understand it is bad.

8. -std=XXX

Set a language standard. Very useful when you strictly want features from a particular standard. For example,


9. -I

gcc -Iexample_dir_name example.c

By default, gcc looks in the current working directory. You can also include multiple other directory locations with -I flag.

10. -D

gcc -Dmacro_name=definition

Define a macro with a value. This is helpful when you want to run the same code in multiple ways such that the code depends on that macro, or maybe for debugging.

For a (very long) list of other such flags, refer to the manpage of gcc (man gcc).
Mention your top gcc flags down in the comments section!

| Cover Pic by Taras Shypka on Unsplash

Posted on by:


markdown guide