Home Programming How to Compile Your First C++ Program with G++ on Linux

How to Compile Your First C++ Program with G++ on Linux

C++ is a programming language that requires to be compiled before run. Despite there are many tools that offer you convenience in developing a C++ based program, there is no bad if you use a command line-based tool to compile your C++ code. Especially if you are new to C++and want to learn everything from the ground.

g++ is a command line-based compiler you can use to compile your C++ code on Linux. This tool comes with a bunch of options, but you will only need the option of “o” to compile your C++ code. This tool has been installed on most Linux distributions by default. To check if this tool is available on your system, you can check it out by typing g++on the terminal. If you find the output like the following, it means that g++ has been installed on your system.

Now that the g++ has been installed on you system, it’s time to compile and run your first C++ program.

I will demonstrate how to use g++ to compile C++ code on Linux with a very standard example, a Hello World program. Below is the code of the program.

#include <iostream>
using namespace std;

int main() 
{
    cout << "Hello, World!\n";
    return 0;
}

Be sure to save your C++ code with the extension of .cpp. Then run the following command to compile it.

g++ hello.cpp -o hello

“hello.cpp” is the raw file (before compiled) of the C++ program, with the code is showed above, while “hello” is the binary/executable file of the program. You can name this file (hello), with your preferred one.

Once the program is compiled, run the following command to run it.

./hello

Be sure to add the “./” symbol.

If the program can’t run, it’s probably because it hasn’t had the executable attribute (+). You can check it by typing ls -lon the terminal.

To add the executable attribute, you can type chmod +x helloon the terminal.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

MOST-READ THIS WEEK