DEV Community

Cover image for GCC Flags Notes
csm
csm

Posted on

GCC Flags Notes

My notes on GNU C Compiler (GCC) Flags

Basic Flags

-c

It tells GCC to compile the source file into an object file (.o), but do not link it into an executable.

gcc -c main.c
Enter fullscreen mode Exit fullscreen mode

This produces:

main.o
Enter fullscreen mode Exit fullscreen mode

Then you can link it separately:

gcc main.o -o main
Enter fullscreen mode Exit fullscreen mode

-o

It specifies the output filename.

gcc main.c -o main
Enter fullscreen mode Exit fullscreen mode

We get:

main
Enter fullscreen mode Exit fullscreen mode

-l

It means "link this library".
For example:

gcc main.c -lm -o main
Enter fullscreen mode Exit fullscreen mode

Here:

  • -l -> link a library
  • m -> library name libm
  • -o main -> output executable named main

The library must be present in the standard search paths of GCC.

-I

It specifies an additional directory to search for header files.

gcc -Iinclude main.c -o main
Enter fullscreen mode Exit fullscreen mode

This tells GCC:
When you see #include "something.h", also look inside the include/ directory.

-L

It specifies an additional directory to search for libraries during linking.
For example:

gcc main.c -L./lib -lmylib -o main
Enter fullscreen mode Exit fullscreen mode

This means:

  • -L./lib -> search ./lib for libraries
  • -lmylib -> link libmylib
  • -o main -> produce main

-static

It tells the linker to create a statically linked executable.

gcc main.c -static -o main
Enter fullscreen mode Exit fullscreen mode

Optimisation

-O

Sets the level of optimisation.

gcc -O2 main.c -o main
Enter fullscreen mode Exit fullscreen mode

Optimisation Levels

  • 0 -> does nothing
  • 1 -> basic optimisation
  • 2 -> produces small binaries
  • 3 -> produces fast binaries (may not be small in size)
1 -> for fast compile times
2 -> for production
0 -> for debugging
Enter fullscreen mode Exit fullscreen mode

Strict Rules, Warnings and Errors

Basic ones are:

-std

It specifies which C standard the compiler should follow.

gcc -std=c17 main.c -o main
Enter fullscreen mode Exit fullscreen mode

-Wall

-Wextra

-Wpedantic

-Werror

Some extra ones:

-W

-Wconversion

-Wshadow

-Wcast-qual

-Wwrite-strings

Debugging Related

-g

It generates debugging information in the executable/object file.

gcc -g main.c -o main
Enter fullscreen mode Exit fullscreen mode

It mainly tells GCC to include information that debuggers such as GDB can use.

Preprocessing Related

-E

It says run only the preprocessor.

gcc -E main.c
Enter fullscreen mode Exit fullscreen mode

-D

It defines a macro from the commmand-line:

gcc -DTEST main.c
Enter fullscreen mode Exit fullscreen mode

Here:

  • -D -> define macro
  • TEST -> name of the macro

Thats it! 😵‍💫

Top comments (0)