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:
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++:
#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:
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:
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.