Compiling C++ code on Linux can seem like a daunting task, but it is actually quite simple if you follow a few basic steps. In this article, we will walk you through the process of compiling C++ code on Linux, including how to install the necessary tools and libraries, how to write a simple C++ program, and how to compile and run your code.
Prerequisites
Before we begin, there are a few prerequisites that you will need to have installed on your Linux system:
- A text editor: This can be any text editor of your choice, such as Vim, Emacs, or Nano.
- A C++ compiler: We will be using the GNU Compiler Collection (GCC) in this article, which should already be installed on most Linux systems.
- The GNU Make build tool: This is a tool for automating the build process of your code. It may already be installed on your system, but if not, you can install it using your package manager.
Writing a Simple C++ Program
Let’s start by writing a simple “Hello, World!” program in C++. Open your text editor and create a new file called hello.cpp
. Add the following code to the file:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
This program simply prints the message “Hello, World!” to the console. Save the file and close your text editor.
Compiling the Program
Now that we have written our C++ program, it’s time to compile it. Open a terminal window and navigate to the directory where you saved hello.cpp
. To compile the program, enter the following command:
g++ -o hello hello.cpp
Let’s break down this command:
g++
: This is the command to invoke the GCC C++ compiler.-o hello
: This option tells the compiler to name the output filehello
.hello.cpp
: This is the name of the input file.
After you run this command, the compiler will generate an executable file called hello
in the same directory as your source file.
Running the Program
To run the program, simply enter the following command in your terminal:
./hello
This will execute the hello
executable, which will print the message “Hello, World!” to the console.
Conclusion
Compiling C++ code on Linux is a straightforward process once you have the necessary tools and libraries installed. In this article, we have shown you how to write a simple C++ program, compile it using the GCC compiler, and run the resulting executable. With this knowledge, you should be well-equipped to start writing and compiling your own C++ programs on Linux.