Boost - Console program menu using boost::program_options

cpp, Boost, Menu, C++

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

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

April 9, 2020, 5:41 a.m.

Qt - Test 001. Signals and slots

  • Result:21points,
  • Rating points-10
April 9, 2020, 5:36 a.m.

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

  • Result:40points,
  • Rating points-8
April 9, 2020, 5:32 a.m.

C++ - Test 001. The first program and data types

  • Result:53points,
  • Rating points-4
Last comments
April 8, 2020, 9:12 a.m.

Круто! Немного начинает проясняться что к чему. Спасибо.
April 7, 2020, 8:55 a.m.

А вот уже и на python... #!/usr/bin/env python# -'''- coding: utf-8 -'''-import sysfrom PySide2.QtWidgets import *from PySide2.QtQuick import *from PySide2.QtCore import *from PySide2.…
April 3, 2020, 8:06 a.m.
Konstantin Grudnitskiy

Я надеюсь вы уже разобрались в чем дело, но если вдруг нет, то проблема состоит в том, что вы пытаетесь запустить программу из интерпретатора питона. Файл это уже готова…
April 3, 2020, 6:18 a.m.
Konstantin Grudnitskiy

>>> text = 'hello world'>>> ' '.join(word for word in text.split()[:-1])'hello'>>> def remove_last_word(text):... return text and ' '.join(word for word in text.s…
March 27, 2020, 2:40 p.m.
Evgenij Legotskoj

Добрый день. В конце пятой статьи скачать можете.
Now discuss on the forum
April 9, 2020, 3:31 a.m.
Dzhon Kofi

Привет. Делаю реализацию перемещения строк на QTableView с моделью QSqlTableModel. Буду в этой теме спрашивать нужное. Пока такой вопрос при создании модели: как мне узнать rowCount? int…
April 8, 2020, 5:42 p.m.

Подскажите как правильно реализовать... Нужно создать массив в C++ с переменными типа сhar или же int. В Qml будет переменная, например text, которая будет изменять своё значение в зависим…
April 8, 2020, 6:29 a.m.
Dzhon Kofi

:-D блин, без слов, пойду пройдусь))
April 8, 2020, 4:59 a.m.

Всем привет. Прошу помощи.есть статическая сборка 5.14.2 (без SSL) компилируется чистый шаблон на QML и Widgets если войти на компьютер в терминальной сессии и запустить программ…
April 6, 2020, 8:06 a.m.

Добрый день. Объясните пожалуйста ... ... допиливать стилевое оформление в прокси классе ... где именно копать ? В каком виртуальном методе лучше допиливать (если можно н…
© EVILEG 2015-2019
Recommend hosting TIMEWEB