boost-program-option用法
# program_options 使用示例
#include <boost/program_options.hpp>
#include <string>
#include <stdint.h>
#include <iostream>
#include <stdio.h>
using namespace std;
namespace po = boost::program_options;
int main(int argc, char **argv)
{
string ip;
uint32_t port;
string ext_flag;
po::variables_map opts_varmap;
po::options_description desc("program desc");
desc.add_options()
("ip,i", po::value<string>(&ip), "first param is ip")
("port,p", po::value<uint32_t>(&port), "second param is port")
("ext_flag,e", po::value<string>(&ext_flag)->default_value(""), "ext flag")
("help,h", "help")
;
// position param
po::positional_options_description pos_desc;
pos_desc.add("ip", 1);
pos_desc.add("port", 1);
try {
po::store(po::command_line_parser(argc, argv).options(desc).positional(pos_desc).run(), opts_varmap);
po::notify(opts_varmap);
} catch(std::exception &e) {
cout << e.what() << std::endl;
return -1;
}
if(opts_varmap.count("help")) {
cout << desc << endl;
return 0;
}
printf("input param: ip=%s, port=%u, ext_flag=%s\n", ip.c_str(), port, ext_flag.c_str());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
使用:
$ ./program_options_demo -i 127.0.0.1 -p 9999 -e flag1
input param: ip=127.0.0.1, port=9999, ext_flag=flag1
$ ./program_options_demo 127.0.0.1 9999 -e flag1
input param: ip=127.0.0.1, port=9999, ext_flag=flag1
$ ./program_options_demo -e flag1 127.0.0.1 9999
input param: ip=127.0.0.1, port=9999, ext_flag=flag1
$ ./program_options_demo
input param: ip=, port=0, ext_flag=
$ ./program_options_demo -h
program desc:
-i [ --ip ] arg first param is ip
-p [ --port ] arg second param is port
-e [ --ext_flag ] arg ext flag
-h [ --help ] help
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
编辑 (opens new window)
上次更新: 2023/05/07, 17:27:54