How to make a simple CLI application in C++

How to make a simple CLI application in C++

In this tutorial, we will learn how to make our command-line application in C/C++ and run it as a normal command in our Linux terminal.

We will make an application that will prompt our Linux distro's name.

  1. First, let us start by making our C++ file. whoareyou.cpp

  2. We will include two libraries "iostream" and "stdlib.h".

#inlcude <iostream>
#include <stdlib.h>
  1. We are including stdlib.h because we need to call system() which we can use to run commands.

  2. Then create the main function.

int main(void) {
    }
  1. And call the system() function with the following parameter -> echo $HOSTNAME

  2. The source code will look something like this.

     #inlcude <iostream>
     #inlucde <stdlib.h>
    
     int main(void) {
         system("echo $HOSTNAME");
         return 0;
     }
    

Now that we have written our C++ code we will compile it, using the following command. g++ -o whoareyou whoareyou.cpp. After compiling we will get an executable file whoareyou. We can simply run it like this ./whoareyou and it will give us an output (which will depend on your host operating system, for me the output is archlinux, as I am using arch). But we want to run it like a normal command in our terminal for that we will need to move the executable file to either ~/.local/bin/ or /bin. /bin is a directory in which all your commands are saved, commands like ls, cd, pwd, mkdir which are pre-installed commands can be found here, and even commands for other packages that you have installed in your system can be found here.

The commands which are installed for all the users can be found in the /bin folder, and in ~/.local/bin/ we can save commands for the current user i.e the commands saved in the ~/.local/bin/ is only available for this user.

You might not have ~/.local/bin already created. Make sure you are on the ~ directory and there you can run the following command ls -la. It will list all your directories. If you don't have that directory you can create it by entering the following commands.

mkdir .local -p
cd .local
mkdir bin

Now go to the directory where you have your executable whoareyou and move it to the ~/.local/bin directory. By executing the following command. cp whoareyou ~/.local/bin/.

And we are done!

Now you can execute whoareyou like any normal command.

This was a really simple example, you can make more complex programs and use them as commands in your Linux operating system.

Till then stay tuned for more amazing articles.