Linux Commands

How to Compile a C++ Program in Linux

Linux offers a strong and adaptable environment for C++ developers to create different cross-platform applications. Executing C++ codes on Linux operating systems is simple since all the C++ tools are preinstalled, allowing users to easily execute codes on the terminal.

As a Linux user, if you need help in compiling C++ code on the system, follow this guide for help.

Compile a C++ Program in Linux

There are two methods to compile a C++ program in Linux:

Method 1: Compile a C++ Program Using Terminal

To compile a C++ program in Linux using terminal, follow the below-given steps:

Step 1: First, open any Linux terminal using Shift+Ctrl+T buttons from the keyboard.

Step 2: Create a .cpp file on Linux using the following command:

nano myfile.cpp

Step 3: Then add any C++ code inside the file.

As an example, below program in which I have used the following code of C++:

using namespace std;

#include<iostream>

int main()

{

  cout << "Any Message";

  return 0;

}

Step 4: Save the file using Ctrl+X, add Y and press enter to exit.

Note: Step 2, 3 and 4 are optional. If you haven’t created a C++ code yet, you can follow them. Otherwise, if you already have C++ code, you can skip these steps.

Step 5: Now, to compile the C++ code, use the following command:

g++ myfile.cpp -o outputfilename

Note: Don’t forget to replace the myfile.cpp with your C++ code file and the outputfile name could be different too.

Step 6: To generate the output of the above code, you need to run the output file:

./outputfile

Method 2: Compile a C++ Program Using IDE

There are built-in IDEs that allow users to run C++ code on Linux systems. The most widely used IDEs on Linux systems are Thonny, Visual Studio Code and CodeBlocks. You can install any of the IDE on your system and start compiling C++ programs on the Linux system.

Conclusion

Linux is a very famous and well-renowned operating system and we can easily compile and run our C++ code on it. You can run C++ code on a Linux system terminal using g++ compiler. While you can also use IDEs like Thonny, VS code or CodeBlocks to compile a C++ program in Linux.

About the author

Kaynat Asif

My passion to research new technologies has brought me here to write for the LinuxHint. My major focus is to write in C, C++, and other Computer Science related fields. My aim is to share my knowledge with other people.