🐧 Linux gcc Command

GNU Compiler Collection (GCC) compiles, assembles, and links C and C++ programs into native executables.

Syntax

$ gcc [options] [source_files] -o output_program

Common Command Options

Option Description
-o Place the output executable into (default is a.out)
-WallEnable all compiler warning messages about questionable constructions
-WextraEnable extra warning flags not included in -Wall
-O2Turn on moderate level 2 code optimization for faster runtime execution
-O3Turn on aggressive optimization (vectorization, inlining)
-gProduce debugging information in native format for GDB
-cCompile and assemble source files, but do not link (creates .o object file)
-std=Specify language standard (e.g. -std=c11, -std=c99, -std=c++17)
-IAdd directory to the search path for header files (#include)
-LAdd directory to the library search path
-lLink with library (e.g. -lm for math library, -lpthread for POSIX threads)

Practical Examples

Simple C Compilation
gcc hello.c && ./a.out
Compiles hello.c into a.out and runs the resulting binary.
Compile with Custom Output Name & Warnings
gcc -Wall -o hello hello.c
Enables all warnings and generates the binary named hello.
Compile Optimized Code with Debugging
gcc -O2 -g -Wall -o myprog main.c
Optimizes performance with -O2 while keeping symbols for GDB.
Link Math Library
gcc -o calc calc.c -lm
Links with the standard C math library (libm.so).
Compile C++ with Modern Standard
g++ -std=c++17 -Wall -o server server.cpp
Uses GNU C++ compiler with C++17 language standard.