Intro

Compiling C++ in Linux using the G++ compiler in the terminal. Most Linux distributions come with g++ (GNU C++ compiler).

g++ is the GNU C++ compiler invocation command used for preprocessing, compilation, assembly, and linking of source code to generate an executable file.

Quick Commands

g++ main.cpp -o program
./program
g++ main.cpp my_computations.cpp -o program

Reference


Installation

Check g++ compiler version

g++ --version

Install if needed

sudo apt install g++

Compile a Single C++ File

Create a main.cpp file

Compile the program

g++ main.cpp -o test_program

Run the program

./test_program

Useful Compiler Flags

  • -Wall β†’ enable common compiler warnings
  • -O2 β†’ optimization level 2
  • -std=c++17 / -std=c++20 / -std=c++23 β†’ specify language standard
  • -g β†’ include debug information for gdb

Example usage:

g++ -std=c++20 -Wall -O2 main.cpp -o program

Compile Multiple Files

Project Structure

project/
β”œβ”€β”€ main.cpp
β”œβ”€β”€ my_computations.cpp
└── my_computations.hpp

main.cpp

Header File

Implementation File


Compile all files

g++ main.cpp my_computations.cpp -o my_program

Run the program

./my_program

Makefile (Automation)

Run:

make

Run program:

./program

Clean build files:

make clean