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.
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
Since it is just a header-only
you can download it directly from the browser or use a utility for this, examples:
wget https://raw.githubusercontent.com/empirical-soft/command-interpreter/refs/heads/master/command_interpreter.hpp
curl -LO https://raw.githubusercontent.com/empirical-soft/command-interpreter/refs/heads/master/command_interpreter.hpp
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/empirical-soft/command-interpreter/refs/heads/master/command_interpreter.hpp"
Let’s create a REPL that has 2 commands:
add
that increments, example: add 3 6
that will display: 9;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.