How to install C++ on Linux

On Linux, you can install the GNU Compiler Collection (GCC), which includes the C++ compiler (g++), through your distribution's package manager. Here are the steps for installing the C++ compiler on Linux, specifically using the apt package manager (common on Debian-based distributions like Ubuntu) and the yum package manager (common on Red Hat-based distributions like CentOS):

Using apt (Debian/Ubuntu)

Open a terminal.

Update the package list to ensure you have the latest information about available packages:

sudo apt update

Install the GCC C++ compiler:

sudo apt install g++

Verify the installation by checking the version of the C++ compiler:

g++ --version

Using yum (CentOS/RHEL)

Open a terminal.

Update the package list to ensure you have the latest information about available packages:

sudo yum update

Install the GCC C++ compiler:

sudo yum install gcc-c++

Verify the installation by checking the version of the C++ compiler:

g++ --version
Example

On Ubuntu 22.04, the following output indicates that the C++ compiler is installed correctly:

g++ (Ubuntu 12.0.1-10ubuntu2) 12.0.1 20220804 Copyright (C) 2022 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Once you have installed the C++ compiler, you can start compiling and running C++ programs.

To compile and run a C++ program from the command line:

  1. Open a terminal window.
  2. Navigate to the directory containing your C++ source code.
  3. Type the following command to compile your C++ program:
g++ *.cpp -o output_file

Replace output_file with the name of the executable file that you want to create.

Type the following command to run your C++ program:

./output_file
Example

The following example shows how to compile and run a simple C++ program called hello_world.cpp:

g++ hello_world.cpp -o hello_world ./hello_world

This will create an executable file called hello_world. You can then run the program by typing ./hello_world.

Congratulations! You have now installed a C++ compiler on Linux and compiled and run a simple C++ program.

Conclusion

To install a C++ compiler on a Linux system, you can use the GNU Compiler Collection (GCC), which includes the C++ compiler (g++). Depending on your Linux distribution, use the appropriate package manager, such as apt for Debian/Ubuntu or yum for CentOS/RHEL, to update the package list and install the "g++" package. Once installed, you can verify the installation by checking the compiler version using the "g++ --version" command.