gcc Command
The gcc command is the GNU Compiler Collection, a powerful compiler system for C, C++, Objective-C, and other programming languages. It's the standard compiler on most Linux systems.
Syntax
gcc [OPTIONS] file...
Description
The gcc command compiles source code files into executable programs or object files. It can handle multiple programming languages and provides extensive optimization and debugging options.
Key features:
- Compiles C, C++, and other languages
- Supports multiple architectures and platforms
- Provides optimization levels
- Generates debugging information
- Links libraries and creates executables
Compilation Process
- Preprocessing: Handles #include, #define, etc.
- Compilation: Converts C code to assembly
- Assembly: Converts assembly to object code
- Linking: Combines object files and libraries
Common Options
| Option | Description |
|---|---|
-o file |
Specify output file name |
-c |
Compile only, don't link |
-g |
Generate debugging information |
-Wall |
Enable all common warnings |
-O2 |
Optimization level 2 |
-l library |
Link with library |
-I directory |
Add include directory |
Examples
Basic compilation
gcc hello.c -o hello
Compiles hello.c into an executable named hello
Compile with debugging information
gcc -g program.c -o program
Includes debugging symbols for use with gdb
Compile with warnings
gcc -Wall -Wextra program.c -o program
Enables comprehensive warning messages
Compile with optimization
gcc -O2 program.c -o program
Applies level 2 optimization for better performance
Compile multiple files
gcc main.c utils.c -o program
Compiles and links multiple source files
Compile to object file only
gcc -c program.c
Creates program.o object file without linking
Link with math library
gcc program.c -lm -o program
Links with the math library (libm)
C++ compilation
gcc program.cpp -lstdc++ -o program
Compiles C++ code (or use g++ instead)