How to Compile and Run a C++ Program in the Linux Terminal
Compiling C++ programs on Linux is a straightforward process that can be achieved using the GNU Compiler, also known as g++. This command-line program converts your high-level language code into an executable file. If you have some knowledge of C++ programming, our main focus is to teach you how to compile and run C++ programs in the terminal.
To compile a C++ program in a Linux terminal using a g++ compiler, follow the below-given steps:
Step 1: First create a cpp file using the nano editor and paste your C++ code in it:
Here I am using the following code as an example.
int main()
{
std::cout << "Hello LinuxHint Followers" << std::endl;
return 0;
}
Save the file using “Ctrl+X”, add “Y” and enter to exit.
Step 2: To compile the program, navigate to the directory in which you saved the .cpp file and run the following command:
Essentially, the -o option specifies the name of the output file that the compiler will create.
Note: If your program includes mathematical functions:
Step 3: Now run the output file using the following command:
This will run our code and gives you the output.
Conclusion
Compiling and running a C++ program in a Linux terminal is a simple procedure that may be achieved by utilizing a few easy commands. Users can quickly compile their code using the g++ command and run their program by executing the resulting binary file. However, they must first create a cpp file, add the C++ code to it and then run the file according to the above-given steps.