gcc Command in Linux

Learn via video courses
Topics Covered

Overview

The GCC command in Linux, which stands for GNU Compiler Collection, is an incredibly powerful tool used primarily for compiling and debugging programs written in C, C++, and other languages. The command gives developers a broad range of control over the compilation process, making it a vital tool in the Linux ecosystem.

Syntax of gcc Command in Linux

The basic syntax of the gcc command in Linux is as follows:

Where:

  • options: These are flags that modify the behavior of the GCC command in Linux.
  • source_files: These are the source code files to be compiled.
  • object_files: These are compiled files that you want to link.
  • -Ldir: This option specifies directories to be searched for libraries.
  • -llibname: This option links the program with a given library.
  • -o outfile: This option defines the name of the output file.

Options in gcc Command in Linux

  1. -o: The -o option is used to specify the name of the output file.

    For example -

    This will compile 'program.c' into an executable named 'program'.

  2. -Wall: The -Wall option enables all compiler's warning messages.

    For example -

    This will compile 'program.c' and display all warning messages.

  3. -g: The -g option enables debugging information.

    For example -

    This will compile 'program.c' with debugging information which is useful for gdb debugger.

Example Usages

  • Simple program compilation:

    Output:

    Explanation: This will compile 'program.c' into an executable named 'a.out'.

  • Compiling program with warnings:

    Output:

    Explanation: This will compile 'program.c' into an executable named 'a.out', showing all warning messages.

Tips

  • Use the -Wall flag to catch common errors and warnings during the development process.

  • To compile programs written in C++, use g++ instead of gcc.

  • Use the -g flag to generate debugging information when dealing with complex code that might require debugging.

Advanced Use Cases of gcc Command in Linux

  • Compiling multiple source files:

    Output:

    Explanation: This command compiles 'main.c', 'program1.c', and 'program2.c' together into an executable named 'a.out'.

  • Linking against a library:

    Output:

    Explanation: This command compiles 'program.c', links the resulting object file with 'libmylib.a' or 'libmylib.so' located in '/opt/lib', and produces an executable named 'program'.

  • Compiling with optimization:

    Output:

    Explanation: This command compiles 'program.c' into an executable named 'a.out' with level 2 optimization.

Conclusion

  • GCC command in Linux is a powerful tool for compiling and debugging programs.

  • Various options of gcc command allow fine control over the compilation process.

  • GCC supports multiple programming languages and allows linking against libraries.