g++(1)
GNU C++ compiler that compiles C++ source code into executables or object files.
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
| Flag | What it does |
|---|---|
-o FILE | Write output to FILE instead of default a.out |
-c | Compile only; produce object files but do not link |
-g | Include debugging symbols for use with gdb |
-O2 | Enable optimization level 2 (good balance of speed and compile time) |
-O3 | Enable optimization level 3 (maximum optimization, slower compile) |
-Wall | Enable all common compiler warnings |
-Wextra | Enable extra warning messages beyond -Wall |
-std=STD | Specify C++ standard (e.g., -std=c++17, -std=c++20) |
-I DIR | Add DIR to header file search path |
-L DIR | Add DIR to library search path |
-l LIB | Link with library LIB (e.g., -lm for math library) |
-D NAME | Define preprocessor macro NAME |
Examples
Compile main.cpp and produce executable myprogram
g++ -o myprogram main.cppCompile with warnings enabled, optimization level 2, C++17 standard, linking multiple source files
g++ -Wall -O2 -o app main.cpp utils.cpp -std=c++17Compile to object files only (main.o and utils.o), no linking
g++ -c main.cpp utils.cppCompile with debugging symbols and all warnings for debugging with gdb
g++ -g -Wall main.cpp -o debug_appLink pre-compiled object files with the math library
g++ main.o utils.o -o myapp -lmCompile with custom header and library paths, linking a custom library
g++ -I/usr/local/include -L/usr/local/lib main.cpp -o app -lcustomCompile with maximum optimization for native CPU architecture
g++ -O3 -march=native main.cpp -o optimized