Create REPL Commands Easily

🚀 With just a header-only!


Create REPL Commands Easily


Command Interpreter is a header-only written in C++ that allows you to create a repl shell with custom commands for you to use as you wish. In this article we will see: dependencies, usage and examples.


Dependencies

To use the Command Interpreter you will need the library: Boost

Use your package manager to install libboost, example on Ubuntu:

sudo apt install libboost-all-dev

Download the Command Interpreter

Since it is just a header-only you can download it directly from the browser or use a utility for this, examples:

GNU/wget on distros GNU/Linux

wget https://raw.githubusercontent.com/empirical-soft/command-interpreter/refs/heads/master/command_interpreter.hpp

cURL for macOS or BSD

curl -LO https://raw.githubusercontent.com/empirical-soft/command-interpreter/refs/heads/master/command_interpreter.hpp

PowerShell no Windows

Invoke-WebRequest -Uri "https://raw.githubusercontent.com/empirical-soft/command-interpreter/refs/heads/master/command_interpreter.hpp"

Code example

Let’s create a REPL that has 2 commands:

  1. add that increments, example: add 3 6 that will display: 9;
  2. inc that increments, example: inc 9 that will display: 10.

main.cpp

#include <iostream>
#include <memory>
#include "command_interpreter.hpp"

class Arithmetic : public CommandInterpreter {
  constexpr static int add(int x, int y) {
    return x + y;
  }

  constexpr int inc(int x) {
    return x + 1;
  }

  void register_commands() override {
    register_command(add, "add", "Add two numbers");
    register_command(&Arithmetic::inc, "inc", "Increment a number");
  }
};

int main(){
  auto a = std::make_unique<Arithmetic>();
  std::string comm;
  std::cout << ">>> ";
  for(;;){
    if(!std::getline(std::cin, comm) || comm == "exit"){
      break;
    }
    std::cout << a->eval(comm) << std::endl;
    std::cout << ">>> ";
  }
  return EXIT_SUCCESS;
}

After compiling and running:

g++ main.cpp -o repl
./repl

Example output:

Typing exit exits the REPL

>>> add 3 6
9
>>> inc 9
10
>>> exit

For more information, visit the repository: https://github.com/empirical-soft/command-interpreter.


cpp cppdaily repl


Share


YouTube channel

Subscribe


Marcos Oliveira

Marcos Oliveira

Software developer
https://github.com/terroo

Related articles