Home / Tutorials / Using GCC

Using GCC

Compiling a Single Source File

The simplest GCC invocation compiles a single C source file into an executable:

gcc hello.c -o hello

This takes hello.c, runs it through preprocessing, compilation, assembly, and linking, and produces an executable called hello. To run it:

./hello

Compiling Multiple Source Files

A typical C project has several source files. You can compile them all in one command:

gcc main.c utils.c network.c -o myprogram

GCC compiles each .c file separately and then links them together into a single executable.

Object Files and Separate Compilation

For larger projects, it is more efficient to compile each source file into an object file (.o) separately, and then link the object files together. This way, when you change one source file, only that file needs to be recompiled.

Compile to object file (no linking yet):

gcc -c main.c -o main.o
gcc -c utils.c -o utils.o
gcc -c network.c -o network.o

Link object files into an executable:

gcc main.o utils.o network.o -o myprogram

The -c flag tells GCC to stop after the assembly phase and produce an object file. It does not attempt to link.

The -g Flag (Debug Information)

The -g flag includes debugging information in the compiled output. This information is required by debuggers like GDB to map machine instructions back to source lines and variable names.

gcc -g main.c -o main

Debug builds are larger than release builds because of the embedded symbol table. Never ship a debug build to end users — use strip or omit -g for release builds.

The -I Flag (Include Paths)

When your code uses header files in non-standard locations, you need to tell GCC where to find them with the -I flag:

gcc -I/usr/local/include -I./include main.c -o main

You can specify multiple -I flags. GCC searches include directories in the order they are specified, before searching the standard system include directories.

Setting Up PATH

GCC needs to be in your PATH environment variable to be invoked as gcc rather than by its full path. On most Linux systems, GCC is installed in /usr/bin or /usr/local/bin, which are typically already in PATH.

To check which GCC is being used:

which gcc
gcc --version

To add a directory to PATH in your shell session:

export PATH=/path/to/gcc/bin:$PATH

To make this permanent, add the export line to your ~/.bashrc or ~/.profile.

Common GCC Flags Summary

Flag Purpose
-o <file> Name the output file
-c Compile to object file, do not link
-g Include debug information
-O0 No optimization (default)
-O1 / -O2 / -O3 Optimization levels 1, 2, 3
-Wall Enable common warning messages
-Wextra Enable extra warnings
-I<dir> Add directory to include search path
-L<dir> Add directory to library search path
-l<lib> Link against library (e.g., -lm for libm)
-std=c99 Use C99 standard
-std=c11 Use C11 standard