$linuxjunkies
>

g++(1)

GNU C++ compiler that compiles C++ source code into executables or object files.

UbuntuDebianFedoraArch

Synopsis

g++ [OPTION]... FILE...

Description

g++ is the GNU C++ compiler, part of the GCC (GNU Compiler Collection). It reads C++ source files and produces executable programs or intermediate object files. g++ automatically links the C++ standard library and handles preprocessing, compilation, assembly, and linking in one command.

g++ accepts .cpp, .cc, .cxx, .c++ and .C files as C++ source. It also handles .c files as C code if preferred. The compiler supports multiple C++ standards (C++98, C++11, C++14, C++17, C++20) and generates optimized machine code for various architectures.

Common options

FlagWhat it does
-o FILEWrite output to FILE instead of default a.out
-cCompile only; produce object files but do not link
-gInclude debugging symbols for use with gdb
-O2Enable optimization level 2 (good balance of speed and compile time)
-O3Enable optimization level 3 (maximum optimization, slower compile)
-WallEnable all common compiler warnings
-WextraEnable extra warning messages beyond -Wall
-std=STDSpecify C++ standard (e.g., -std=c++17, -std=c++20)
-I DIRAdd DIR to header file search path
-L DIRAdd DIR to library search path
-l LIBLink with library LIB (e.g., -lm for math library)
-D NAMEDefine preprocessor macro NAME

Examples

Compile main.cpp and produce executable myprogram

g++ -o myprogram main.cpp

Compile with warnings enabled, optimization level 2, C++17 standard, linking multiple source files

g++ -Wall -O2 -o app main.cpp utils.cpp -std=c++17

Compile to object files only (main.o and utils.o), no linking

g++ -c main.cpp utils.cpp

Compile with debugging symbols and all warnings for debugging with gdb

g++ -g -Wall main.cpp -o debug_app

Link pre-compiled object files with the math library

g++ main.o utils.o -o myapp -lm

Compile with custom header and library paths, linking a custom library

g++ -I/usr/local/include -L/usr/local/lib main.cpp -o app -lcustom

Compile with maximum optimization for native CPU architecture

g++ -O3 -march=native main.cpp -o optimized

Related commands