Evgenii Legotckoi
Evgenii LegotckoiNov. 18, 2018, 5:57 a.m.

Boost - Console program menu using boost::program_options

And here is an article on the boost of my some accumulated materials. I offer you the option of writing a console program with support for the console menu, which is implemented using boost::program_options .

boost::program_options is responsible for processing the arguments passed to the program and sets all the necessary variables without the need to implement long logic from if else branches. This is already implemented inside boost::program_optons .

Suppose our program takes the following data as arguments

  • input file path
  • output file path
  • the size of the block being processed, no matter why, we will not do anything with it, just have such a parameter in the program.

Also, the program will have a help menu, which will be the console menu.

The figure below shows the use of this program.


Project structure

This program will be written using the CMake build system, without using the Qt library . This will be a tutorial purely for boost.

Посмотрим на структуру проекта.

В данном проекте есть

  • CMakeLists.txt -  CMake configuration file
  • main.cpp - file with main function
  • EApplication.h - header file of the main class of the application
  • EApplication.cpp - source file of the main application class

We write a project using OOP.

CMakeLists.txt

To begin with, let's deal with the configuration of the project, since this project is written using the boost library, it needs to be configured to work.

I note that this project was created under the Linux operating system, so there may be differences in the settings under the Windows or Mac OS.

Also, if you do not have the Boost development kit, then for example under Ubuntu you can do it like this

sudo apt-get install libboost-all-dev

Look at the project setup

cmake_minimum_required(VERSION 3.12)
project(Menu)

set(CMAKE_CXX_STANDARD 17)

find_package(Boost 1.58.0 COMPONENTS filesystem program_options)

set(SOURCE_FILES
        main.cpp
        EApplication.cpp
        EApplication.h)

if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    add_executable(Menu ${SOURCE_FILES})
    target_link_libraries(Menu ${Boost_LIBRARIES})
endif()

As you can see, I connected the standard C ++ 17. In this case, it does not matter, you can build the project and the standards C + + 11 or C + + 14.

This is the minimum required version of CMake. This version was installed on my PC.

Then we look for the boost components we need.

  • filesystem - we will save information about the file
  • program_options - to form a console menu

The if enfif condition specifies the libraries, their header files, and the source files of the project.

main.cpp

Let's look at the contents of the file with the main function. An application instance will be created there and its exec () method will be executed to run the main program logic.Let's look at the contents of the file with the main function. An application instance will be created there and its exec () method will be executed to run the main program logic..

#include <iostream>

#include "EApplication.h"

int main(int argc, const char* argv[])
{
    EApplication app(argc, argv);
    return app.exec();
}

EApplication.h

And now the most interesting, the program itself with the console menu.

#ifndef MENU_EAPPLICATION_H
#define MENU_EAPPLICATION_H

#include <boost/program_options.hpp>
#include <boost/filesystem/fstream.hpp>

namespace po = boost::program_options;
namespace fs = boost::filesystem;

class EApplication
{
public:
    explicit EApplication(int argc, const char** argv);

    int exec();

private:
    // And now the most interesting, the program itself with the console menu.
    po::options_description m_desc {"Allowed options"};
    po::variables_map m_vm; // container for saving selected program options

    // Required variables for working with menu options
    size_t m_blockSize;
    fs::path m_inputFilePath;
    fs::path m_outputFilePath;
};


#endif //MENU_EAPPLICATION_H

EApplication.cpp

#include "EApplication.h"

#include <iostream>

EApplication::EApplication(int argc, const char **argv)
{
    // Add menu items
    m_desc.add_options()
            ("help", "produce help message")  // Help
            ("input-file,i",  po::value<fs::path>(&m_inputFilePath)->composing(), "set input file path")              // Input file, you can write either --input-file, or -i
            ("output-file,o", po::value<fs::path>(&m_outputFilePath)->composing(), "set output file path")            // Output file
            ("block-size,b",  po::value<size_t>(&m_blockSize)->default_value(1024 * 1024), "set block size in bytes") // Block size
            ;
    po::store(po::parse_command_line(argc, argv, m_desc), m_vm);  // parse passed arguments
    po::notify(m_vm); // write arguments to variables in the program
}

int EApplication::exec()
{
    // If there is a request for help
    if (m_vm.count("help"))
    {
        // Then we display the menu description
        std::cout << m_desc << std::endl;
        return 1;
    }

    // If at least input and output parameters were entered
    if (m_vm.count("input-file") && m_vm.count("output-file"))
    {
        // then we initialize the program, but in this case we only display information about the entered parameters
        std::cout << m_inputFilePath << '\t' << m_outputFilePath << '\t' << m_blockSize << std::endl;
    }
    else
    {
        // Otherwise, we offer to see the help.
        std::cout << "Please, use --help option for information" << std::endl;
        return 1;
    }

    // ToDo something
    // Here we can put program logic in a while() or for(;;) loop

    return 0;
}

Conclusion

This library boost::program_options is really very useful and allows you to get rid of a large number of problems when writing the console menu. At a minimum, it allows you to write a very compact program code, and also very quickly implement the menu in a console application.

Git Repository Link

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
i
innorwallNov. 14, 2024, 12:07 p.m.
Circuit switching and packet data transmission networks Angioedema 1 priligy dapoxetine
i
innorwallNov. 14, 2024, 11:42 a.m.
How to Copy Files in Linux If only females relatives with DZ offspring were considered these percentages were 23 order priligy online uk
i
innorwallNov. 14, 2024, 9:09 a.m.
Qt/C++ - Tutorial 068. Hello World using the CMAKE build system in CLion ditropan pristiq dosing With the Yankees leading, 4 3, Rivera jogged in from the bullpen to a standing ovation as he prepared for his final appearance in Chicago buy priligy pakistan
i
innorwallNov. 14, 2024, 4:05 a.m.
EVILEG-CORE. Using Google reCAPTCHA 2001; 98 29 34 priligy buy
i
innorwallNov. 14, 2024, 4 a.m.
PyQt5 - Lesson 007. Works with QML QtQuick (Signals and slots) priligy 30mg Am J Obstet Gynecol 171 1488 505
Now discuss on the forum
i
innorwallNov. 14, 2024, 3:39 a.m.
добавить qlineseries в функции priligy amazon canada 93 GREB1 protein GREB1 AB011147 6
i
innorwallNov. 11, 2024, 10:55 a.m.
Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks