How to Compile C++ in Linux [Step-By-Step]


You can write many important programming languages on Linux, including C++. Linux allows you to get started without doing so much, and you can do it from the command line. However, to get started, you will have to follow a few steps. This article will teach you how to write C++ programs in Linux.

If you want to start using C++, you will need a text editor, such as Notepad, to write the C++ code. You will also need a compiler, such as GCC, to translate the C++ code into a language that the computer understands. There are lots of text editors and compilers that you can choose from.

Writing C++ programs in Linux

This section will work you through the steps to follow to write C++ programs in Linux. The first thing you will have to do is install the C++ compiler on the Linux box. To do that, you need to follow the guidelines below.

Step 1: – Installing C++ Compiler on Linux Box

In your Linux (CentOS, Red Hat or Fedora) machine, type in the following command as root to install the C++ compiler:

yum install -y gcc-c++*

Step 2: – You need to verify if the GCC compiler was installed successfully

Use the rpm –qa command:

[root@server01 ~]#  rpm –qa | grep –I c++

libstdc++-4 . 4 . 7-3 . el6 . i686

libstdc++-devel-4 . 4 . 7-3 . el6 . i686

[root@server01 ~]#

Use the Which command:

[root@server01 ~]# which c++

/usr/bin/c++

[root@server01 ~]#

Step 3: – Now, you can write your First C++ Program on Linux

I will show you how to write your first C++ program with “Hello, this is my C++ program on Linux.” This is a basic example and is very suitable for beginners to follow. If you are not familiar with it, you should know that all it does is print the phrase “Hello, this is my C++ program on Linux” on your screen.

To get started:

  1. You need to access your terminal and open a new file to enable you to edit and use the vim command:

vim hello.cc

  1. Now, in the vim editor, type in the following code:

#include <iostream>

using namespace std;

int main()

{

 cout << “Hello, this is my C++ program on Linux” << endl;

 return 0;

}

  1. Once you finish, save and exit the file
  2. You need to compile your new C++ program by typing the following command from your terminal:

c++ hello.cc

If the compilation is free of errors, no output will be displayed.

[root@server01 ~]# c++ hello.cc

[root@server01 ~]#  

  1. You will now see an executable file created in the current directory, with the default name a.out.
  2. To run the program, you have to execute the generated executable the same way you execute a Linux executable. Congratulations, now you have written your first program on Linux.

Step 4: You should specify the name for the resulting executable.

As mentioned earlier, when you compile C++ programs without specifying options as we did above, you will receive an executable file named a.out. However, if you want to specify a name of your choice for the resulting executable, there are two ways to do that. They include the following:

  1.  You can rename the default a.out after it is created.
  2. You can specify the executable filename on compilation using the –o option.

c++ hello.cc -o /opt/hello.run

When you execute the named executable, you should get the same output:

[root@server01 ~]#  /opt/hello. run

Hello, this is my C++ program on Linux

[root@server01 ~]#  

Step 5: – Execute System Commands from C++ Programs

Being able to communicate with the system by executing operating system commands on need is important. With the system’s () function, you can run system commands from the C++ code. If you want the compiler to recognize this function and compile it successfully, you need to invoke the stdlib.h library file.

For instance, you can write a program that displays the system info given below:

Hostname

IP address

Date and time

File systems utilization

Type in the following code in a new file (say system_commands.cc)

#include <iostream>

#include <stdlib.h>

using namespace std;

int main()

{

        system(“echo -n ‘\nHostname: ‘”); system(“hostname”);

        system(“echo -n ‘\nIP Address: ‘”); system (“ip a”);

        system(“echo -n ‘\nDate/Time: ‘”); system (“date”);

        system(“echo ‘\n Filesystem Utilization:'”); system(“df -h; echo”);

 return 0;

}

Compile the source file:

[root@server01 ~]#  c++ system_commands . cc –o SysCheck

[root@server01 ~]#  

  1. Now, you should execute it:

[root@server01 ~]#  ./SysCheck

Hostname: server 01

IP Address: 1: lo: <LOOPBACK , UP , LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN

 link/loopback 00 : 00 : 00 : 00 : 00 : 00 brd 00 : 00 : 00 : 00 : 00 : 00

inet 127 . 0 . 0 . 1/8 scope host lo

inet6 : : 1/128 scope lost

      valid_lft forever preferred_lft forever

   3:   eth: <BROADCAST ,MULTICAST ,UP , LOWER_UP> mtu 1500 qfifo_fast state UP qlen 1000

link/ether 08 : 00 : 27 : 67 : 27 : 92 brd ff : ff : ff : ff : ff : ff

inet 192 . 168 . 1 . 100/24 brd 192 . 168 . 1 . 255 scope global eth1

inet6 fe80 : : a00 : 27ff : fe67 : 27ff : fe67 : 2792/64 scope link

        valid_lft forecer preferred_lft forever

Date/Time: Sat Oct 3 20: 34: 12 EET 2020

Filesystem Utilization:

Filesystem size Used Avail Use Mounted on

/dev/mapper/ volGroup-lv_root

6.9G 4.7G 1.9G 72 /

tmpfs 134M 0 134M 0 / dev/shm

/dev/sdal 485M 27M 433M 6 /boot

/ dev/loop0 3.6G 3.6G 0 100 /cdrom

[root@server01 ~]#  

Step 6: – The getpid() and getppid() Functions

If you want to get the Process ID (PID) of the current process, you need to use the getpid().

For example, the following program prints the process ID of the program:

#include <iostream>

#include <unistd.h>

using namespace std;

int main()

{

        pid_t PID;

        PID = getpid();

        cout << “The PID of the current process: ” << PID << endl;

        return 0;

}

You should compile and execute the program:

[root@newcentos ~]#  c++ getPID . cc –o getPID

[root@newcentos ~]#  

[root@newcentos ~]#  ./getPID

The PID of the current process: 1534

[root@newcentos ~]#  

Take note of the pid_t data type – a numeric data type that is normally used for process IDs. The getppid() function is for returning the process ID of the parent process.

For instance, you can modify the previous program to print the PPID also.

#include <iostream>

#include <unistd.h>

using namespace std;

int main()

{

        pid_t PID,PPID;

        PID = getpid();

        PPID = getppid();

        cout << “The PID of the current process: ” << PID << endl;

        cout << “The PID of the parent process: ” << PPID << endl;

        return 0;

}

When you write and execute this program, it should print both the process ID of the program and its parent process ID.

Step 7: – The fork() Function

You can create a new (child) process using the fork() function. To do this, you need to duplicate the calling (parent) process. This function is used for returning the PID of the new child process if success. If it fails, -1 will be returned instead. In the child process, 0 will be returned on success.

For instance, the following program gets a child process started. If this operation succeeded, the PIDs of both the current and child processes would be printed. If it fails, the program prints a message stating that it failed to start the child process.

#include <iostream>

#include <unistd.h>

using namespace std;

int main()

{

        pid_t PID,CPID;

        PID = getpid();

        CPID = fork();

        if(CPID<0)

        {       cout << “Error starting child process\n”;

                return 1;

        }

        else

        {

                cout << “The PID of the current process: ” << PID << endl;

                cout << “The PID of the new child process: ” << CPID << endl;

        }

        return 0;

}

Let us look at the result when this program is run:

[root@server01 ~]# g++ fork. Cc –o fork

[root@server01 ~]#

[root@server01 ~]# ./fork

The PID of the current process: 1600

The PID of the new child process: 1601

The PID of the child process: 1600

The PID of the new child process: 0

[root@server01 ~]#

You should note that the child process is a copy of the parent. And this is why four lines got printed, instead of two. Also, take note of the discrepancy between the child process ID’s values, which is inside the parent. The child’s process ID will be returned by the fork() function and printed. 

On the other hand, the fork() function will return 0 to the child process. If you want to learn more about the C++ programming language, you can check out this link.

Conclusion

If you want to write C++ programs on Linux machines, you will need the GCC compiler. C++ programs can be written and saved as .cc files, and you can do it by following the steps detailed in this article. In all, I hope this guide was helpful, and you now know how to compile C++ on Linux.

Recent Content