Handwriting C++ server (8): Commonly used boost program_options command line parameter analysis

Foreword: As the most important extension library of C++, boost is an indispensable "weapon" for C++ programming with its wide range of use, high performance, perfect technical atmosphere, strong portability and open source code. The topic of Handwriting C++ Server will introduce some of the most commonly used boosts. This article introduces program_options for command line parameter parsing. Let’s start with the common argc and argv, and open the world of program_options together!

table of Contents

int argc, char *argv[]

argc and argv[] meaning

for example

program_options

Advantages and official website address

Component

manual

Programming example

Compile and run


int argc, char *argv[]

This way of writing is very common when passing command line parameters:

int main (int argc, char *argv[])

If you do not need to pass command line parameters, there is no problem with using void instead. So, what is the use of this way of writing?

argc and argv[] meaning

argv and argc are the way command line parameters are passed to main() in C and C++.

  • argc: parameter count. The total number of parameters on the command line +1 . The first parameter is the name of the program .
  • argv: parameter vector. The specific parameters of the command line are stored in the vector.

Note: This is just a convention, these variables are named argc (parameter count) and argv (parameter vector). But they can be assigned any valid identifier : int main(int num_args, char** arg_strings) is also valid.

for example

vim argv_argc.cpp
#include <iostream> int main(int argc, char *argv[]) {    std::cout << "Have" << argc << "arguments:" << std::endl;    for (int i = 0; i < argc; i++) {        std::cout << argv[i] << std::endl;    }}

Compile:

g++ argv_argc.cpp -o argv_argc

run:

./argv_argc a1 b2 c3 d4Have 5 arguments:./argv_argca1b2c3d4

If it is changed to int main (void), a compilation error will be reported:

g++ argv_argc_void.cpp -o argv_argc_voidargv_argc_void.cpp: In function ‘int main()’:argv_argc_void.cpp:4:28: error: ‘argc’ was not declared in this scope     std::cout << "Have" << argc << "arguments:" << std::endl;                            ^~~~argv_argc_void.cpp:6:22: error: ‘argv’ was not declared in this scope         std::cout << argv[i] << std::endl;                      ^~~~

program_options

Advantages and official website address

The argc and argv just introduced can get command line parameters, but boost provides a more powerful command line parameter library program_options. The advantages of program_options are as follows:

  • Simple and easy to learn.
  • The syntax for declaring options is simple, and the library itself is small. Things such as converting option values ​​to the required types and storing them in program variables are handled automatically.
  • Error reporting is better. All problems with the command line will be reported, and the handwritten code may just misinterpret the input. In addition, usage messages can be automatically generated to avoid getting out of sync with the real option list.

The best way to learn is the official website manual , here is the address of the official website tutorial:

https://www.boost.org/doc/libs/1_75_0/doc/html/program_options/tutorial.html

Component

Component nameeffect
options_description (option descriptor)Describe which options are defined in the current program
parse_command_line (option analyzer)Parse the parameters entered by the command line
variables_map (option memory)Container, used to store parsed options

manual

1. Include header files

#include <boost/program_options.hpp>

2. Construct a namespace

namespace bpo = boost::program_options;

3. Construct option descriptor and option memory

bpo::options_description opts("all options");bpo::variables_map vm;

4. Add options in the option descriptor

      opts.add_options ()          ("help,h", "produce help message")          ("compression,c", bpo::value<int>(), "set compression level")          ("filename,f", bpo::value<std::string>(), "the file name which want to be found");

5. Parameter analysis && exception handling

    try {        bpo::store(bpo::parse_command_line(argc, argv, opts), vm);    } catch (...) {        std::cout << "input undecleare options!" << std::endl;    }

6. Judgment options

    if (vm.count("help")) {        std::cout << opts << std::endl;    }    if (vm.count("filename")) {        // 取出后的类型是boost::any,需要通过模板成员函数as<type>()做类型转换,才能获取具体值        std::cout << "find: " << vm["filename"].as<std::string>() << std::endl;    }    if (vm.empty()) {        std::cout << "input is empty!" << std::endl;    }

Programming example

#include <iostream>#include <boost/program_options.hpp>#include <string> int main (int argc, char *argv[]) {    // 步骤一:构造命名空间    namespace bpo = boost::program_options;     // 步骤二:构造选项描述器    bpo::options_description opts("all options");    // 步骤二:构造选项存储器,用法和map类似    bpo::variables_map vm;     // 步骤三:为选项描述器添加选项    opts.add_options ()        ("help,h", "produce help message")        ("compression,c", bpo::value<int>(), "set compression level")        ("filename,f", bpo::value<std::string>(), "the file name which want to be found");     // 步骤四:对命令行输入参数做解析,并存入选项存储器中    // 捕获异常    try {        bpo::store(bpo::parse_command_line(argc, argv, opts), vm);    } catch (...) {        std::cout << "input undecleare options!" << std::endl;    }     // 步骤五:notify更新所有外部变量    bpo::notify(vm);     // 步骤六:对解析完的参数处理    // count用来判断在选项存储器中是否存在这个选项    if (vm.count("help")) {        std::cout << opts << std::endl;    }    if (vm.count("filename")) {        // 取出后的类型是boost::any,需要通过模板成员函数as<type>()做类型转换,才能获取具体值        std::cout << "find: " << vm["filename"].as<std::string>() << std::endl;    }    if (vm.empty()) {        std::cout << "input is empty!" << std::endl;    }     return 0;}

Compile and run

Remember to add -lboost_program_options when compiling

g++ boost_program_options.cpp -o boost_program_options -lboost_program_options

run:

./boost_program_options -hall options:  -h [ --help ]            produce help message  -c [ --compression ] arg set compression level  -f [ --filename ] arg    the file name which want to be found
./boost_program_options -f=boost_program_optionsfind: =boost_program_options
./boost_program_options -finput undecleare options!input is empty!

reference: