Evgenij LegotskojNov. 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.


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)


find_package(Boost 1.58.0 COMPONENTS filesystem program_options)


    add_executable(Menu ${SOURCE_FILES})
    target_link_libraries(Menu ${Boost_LIBRARIES})

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.


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();


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


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

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

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

    int exec();

    // 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;



#include "EApplication.h"

#include <iostream>

EApplication::EApplication(int argc, const char **argv)
    // Add menu items
            ("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;
        // 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;


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.
Support the author Donate


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

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting

C++ - Тест 003. Условия и циклы

  • Result:0points,
  • Rating points-10

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

  • Result:50points,
  • Rating points-4
  • Mili
  • Feb. 18, 2021, 9:22 a.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
  • t1m4
  • Feb. 24, 2021, 2:56 a.m.

Django - Tutorial 052. Redefining a User Model

В данном случае я заходил под superuser но все равно не появлялись эти поля

Django - Tutorial 001. Deploying a site on Django + PostgreSQL + Gunicorn + Nginx

Поднял сервис с помощью systemd, вот по этому мануалу: https://habr.com/ru/post/501414/
  • t1m4
  • Feb. 23, 2021, 7:11 a.m.

Django - Tutorial 052. Redefining a User Model

А как дать ему эти права?

Django - Tutorial 001. Deploying a site on Django + PostgreSQL + Gunicorn + Nginx

Всё по мануалу выше, буква в букву. gunicorn mysite.wsgi:application server { listen 80; server_name; access_log /var/log/nginx/example.log; locat…
Now discuss on the forum

нужна помощь с проектом qt c++

дали задание, на несколько дней. собираюсь делать, но хотел бы получить помощь более опытных людей, чтобы подкорректировать себя и подстраховаться. каким образом это можно сделать? …

QScrollArea dynamically add QCheckBoxes

Всё правильно. Это просто спамер, который отправился в вечный бан.

При рендере тайлов появляется buffer reallocation

upd. с помощью double commander в сырцах OpenStreetMap плагина нашёл такую функцию size_t CoordBuffer::PushCoord(double x, double y) { if (usedPoints>=bufferSize) { buff…

Сигналы и слоты в PyQt5

Решение стало следующим: после конвертации файла Ui из QtDesigner мне никак не выгодно продолжать работать в этом же файле, т.к. я постоянно продолжаю дорабатывать интерфейс, а его поведение я о…

Получение даты сборки программы

Проблему решил так: В .pro файле: VERSION = 1.2.3DEFINES += APP_VERSION=\\\"$$VERSION\\\"#Формирование даты и времени сборки (меняется при полной пересборке проекта)win32:{BLD_DATE=…
© EVILEG 2015-2020
Recommend hosting TIMEWEB