Search code examples
c++boostboost-program-options

Getting boost program options to persist after function scope


I have a function which takes a boost::program_options::options_description, adds some options, then returns the thing back. It seems as though my options are not persisting after the scope of the function ends, and my options disappear. How do I get them to persist?

#include <boost/program_options.hpp>
#include <utility>


void generic_args(boost::program_options::options_description desc, boost::program_options::positional_options_description p) {
    desc.add_options()
        ("input", boost::program_options::value<std::vector<std::string>>(), "input files")
        ("help,h", "produce help message")
        ("verbose,v", "put the pretty words and numbers on the light screen");

    p.add("input", -1);
}

int main(int argc, const char** argv) {
    boost::program_options::options_description desc("Allowed options");
    boost::program_options::positional_options_description p;
    generic_args(desc, p);
    boost::program_options::variables_map parameters;
    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(p).run(), parameters);
    boost::program_options::notify(parameters);
    return 0;
}

Here's the output:

scott@beast:~/test/test_args$ g++ -std=c++11 main.cpp -o a.out -lboost_program_options
scott@beast:~/test/test_args$ ./a.out
scott@beast:~/test/test_args$ ./a.out --help
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::program_options::unknown_option> >'
  what():  unrecognised option '--help'
Aborted (core dumped)

Solution

  • You should change generic_args to take the arguments by reference:

    void generic_args(boost::program_options::options_description &desc,
                      boost::program_options::positional_options_description &p)
    {
      // ...
    }
    

    currently generic_args modifies a copy of desc and p (they're passed by value).

    Take a look at Does C++ pass objects by value or reference? and What's the difference between passing by reference vs. passing by value? for further details.