2.4.2. age.cpp#

2.4.2.1. Source code#

 1// University of Florida EEL6528
 2// Tan F. Wong
 3// Jan 8, 2021
 4
 5#include <uhd/utils/safe_main.hpp>
 6#include <boost/program_options.hpp>
 7#include <csignal>
 8 
 9namespace po = boost::program_options;
10
11// Interrupt signal handlers
12static bool stop_signal_called = false;
13void sig_int_handler(int) {
14    stop_signal_called = true;
15}
16 
17int UHD_SAFE_MAIN(int argc, char *argv[]) {
18 
19    //variables to be set by po
20    std::string name;
21    int age;
22 
23    //setup the program options
24    po::options_description desc("Allowed options");
25    desc.add_options()
26        ("help", "help message")
27        ("name,n", po::value<std::string>(&name)->default_value("This person"), "The person's name")
28        ("age,a", po::value<int>(&age)->default_value(-1), "The person's age")
29        ("nice-print", "Print out the info nicely")
30    ;
31 
32    po::variables_map vm;
33    po::store(po::parse_command_line(argc, argv, desc), vm);
34    po::notify(vm);
35 
36    //print the help message
37    if (vm.count("help")) {
38        std::cout << desc << std::endl;
39        return EXIT_SUCCESS;
40    }
41
42    std::signal(SIGINT, &sig_int_handler);
43
44    // Keep running until CTRL-C issued
45    while (not stop_signal_called) {
46        if (vm.count("nice-print")) { 
47            // nice printing
48            if (age < 0) {
49                std::cout << name <<  "'s age is unknown." << std::endl;
50            } else {
51                std::cout << name << " is " << age << " years old." << std::endl;
52            }
53        } else {
54            // not nice printing
55            std::cout << "Name = " << name << std::endl;
56            std::cout << "Age = " << age << std::endl;
57        }
58        sleep(1); // Just don't print too fast
59    }
60 
61    std::cout << std::endl;
62    return EXIT_SUCCESS;
63}

2.4.2.2. Build#

  • Need to link the uhd and boost_program_options libraries when compiling:

     $ g++ age.cpp -o age -luhd -lboost_program_options
    

2.4.2.3. Usage examples#

$ ./age --help
Allowed options:
  --help                           help message
  -n [ --name ] arg (=This person) The person's name
  -a [ --age ] arg (=-1)           The person's age
  --nice-print                     Print out the info nicely
$ ./age
Name = This person
Age = -1
Name = This person
Age = -1
^C
$ ./age --nice-print
This person's age is unknown.
This person's age is unknown.
This person's age is unknown.
^C
$ ./age --nice-print --name=Tom -a 25
Tom is 25 years old.
Tom is 25 years old.
Tom is 25 years old.
Tom is 25 years old.
^C