gcc Command: Tutorial & Examples

Compile C files into executables using the GNU Compiler Collection

The gcc command is the GNU Compiler Collection, a powerful set of compilers primarily used to translate C and C++ source code into executable programs. It is an essential tool for software development on Linux servers and virtual machines, enabling developers to convert human-readable code into machine-executable instructions through a multi-stage process.

This article explains how gcc works, its common usage patterns, important command line options, practical examples, and troubleshooting tips. By the end, you will understand how to use gcc effectively to compile, debug, and optimize your programs from the command line.

How It Works

The gcc command processes your source code in several distinct stages to produce an executable file:

  1. Preprocessing: Handles directives starting with # such as #include and #define. It expands macros and includes header files to prepare a pure source code stream for compilation.

  2. Compilation: Translates the preprocessed source code into assembly language for the target architecture.

  3. Assembly: Converts the assembly code into machine code, producing an object file (.o).

  4. Linking: Combines one or more object files and libraries into a single executable program. This step resolves references to external symbols such as functions or variables.

Each stage can be controlled separately with command line options, allowing advanced users to inspect intermediate outputs or optimize specific phases.

What It Is Used For

gcc is primarily used to compile programs written in C and C++, but it also supports other languages like Objective-C and Fortran through additional frontends. On Linux servers and VMs, gcc is invaluable for:

  • Building software from source code.
  • Debugging programs with included debug symbols.
  • Optimizing executable size and performance.
  • Linking with libraries to extend functionality.
  • Automating builds via scripts and makefiles.

Without gcc or a similar compiler, source code remains human-readable text and cannot be executed by the computer.

Why It Is Important

The gcc compiler is a cornerstone of development in the Linux ecosystem. Because Linux servers often run software compiled from source for performance or customization reasons, gcc allows sysadmins and developers to:

  • Build and maintain custom applications.
  • Compile security patches and updates.
  • Debug and profile programs.
  • Cross-compile code for different architectures.

Its open-source nature and wide platform support make it the default compiler on most Linux distributions.

How To Use It

The general syntax of the gcc command is:

gcc [options] [source files] [object files] [-o output file]

Basic Examples

  • Compile a single C source file to the default executable a.out:

    gcc program.c
    
  • Compile and specify output filename:

    gcc program.c -o program
    
  • Compile multiple source files together:

    gcc file1.c file2.c -o myapp
    
  • Compile without linking (produce object file):

    gcc -c program.c
    

This creates program.o, an object file.

Common Command Line Parameters

  • -o file
    Specifies the output file name instead of the default a.out.

  • -g
    Includes debug information in the executable, useful for debugging tools like gdb.

  • -c
    Compile or assemble the source files, but do not link. Produces object files.

  • -Wall
    Enables most compiler warning messages to help detect potential issues.

  • -Werror
    Treats all warnings as errors, stopping compilation if warnings occur.

  • -O[level]
    Optimization level, where [level] can be 0 (no optimization), 1, 2, 3, or s for size optimization.

  • -I directory
    Adds the specified directory to the list of directories to search for header files.

  • -L directory
    Adds the specified directory to the list of directories to search for libraries during linking.

  • -l library
    Links against the specified library (e.g., -lm for math library).

Practical Examples Using gcc

  • Compile with all warnings enabled and output named app:

    gcc -Wall program.c -o app
    

    Sample output on success: (no output)
    If warnings exist, you might see lines like:

        program.c:10:5: warning: implicit declaration of function ‘foo’ [-Wimplicit-function-declaration]
    
  • Compile with debugging symbols for gdb:

    gcc -g program.c -o debug_app
    
  • Compile multiple files with linking:

    gcc main.c utils.c -o myprogram
    
  • Compile without linking (produce object files):

    gcc -c utils.c
    

    This creates utils.o.

  • Link object files and libraries:

    gcc main.o utils.o -lm -o final_app
    

    Here -lm links the math library.

Common Errors And Troubleshooting

  • Syntax Errors:
    If your source code contains syntax errors, gcc will report errors like:

        program.c:5:10: error: expected ‘;’ before ‘return’
    

    Fix the code accordingly.

  • Linker Errors:
    Occur when references to functions or variables cannot be resolved during linking, e.g.:

        /usr/bin/ld: undefined reference to `foo'
    

    Make sure all source files or libraries are included.

  • Missing Header Files:
    Errors like:

        program.c:2:10: fatal error: myheader.h: No such file or directory
    

    Use -I to add directories or install the required headers.

  • Permission Errors:
    If you cannot write the output file, check your permissions for the directory.

Tips And Best Practices

  • Always use -Wall to enable warnings and catch potential issues early.
  • Use -Werror in CI environments to enforce clean builds.
  • For debugging, compile with -g and avoid optimization (-O0).
  • Use make or other build tools to automate compilation for larger projects.
  • Keep source files and object files organized in separate directories.
  • Use -std=c11 or other standards flags to specify language standard.
  • Regularly update your gcc version for new features and bug fixes.

Possible Alternatives Or Related Commands

  • g++ — The C++ compiler front-end, often invoked as g++, part of the same gcc package.
  • clang — An alternative compiler with modern features and better error messages.
  • make — A build automation tool that simplifies compiling multi-file projects.
  • ld — The linker used internally by gcc.

Cheatsheet

  • gcc file.c — Compile file.c to a.out.
  • gcc file.c -o output — Compile and name output output.
  • gcc -c file.c — Compile only, create file.o.
  • gcc -Wall -Werror file.c — Enable warnings and treat them as errors.
  • gcc -g file.c -o debug — Compile with debug symbols.
  • gcc file1.c file2.c -o app — Compile multiple source files.
  • gcc file.o -lm -o app — Link object file with math library.

See Also

Further Reading

As an Amazon Associate, I earn from qualifying purchases.

The text above is licensed under CC BY-SA 4.0 CC BY SA