Linux Commands

How to Compile and Run a C++ Program in a Linux Terminal

For many developers, Linux is an ideal environment to write C++ code because of its open-source nature and powerful compiler. However, compiling and running C++ programs on Linux could be intimidating for users who are not familiar with the procedure. Fortunately, with the right instructions and tools, it can be made simple. This tutorial aims to guide you through the process of compiling and running C++ programs on Linux, breaking it down into easy-to-follow stages.

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:

nano filename.cpp

Here I am using the following code as an example.

#include <iostream>

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:

g++ -o output_file filename.cpp

Essentially, the -o option specifies the name of the output file that the compiler will create.

Note: If your program includes mathematical functions:

g++ -o output_file filename.cpp -lm

Step 3: Now run the output file using the following command:

./output

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.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.