Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle command line options and config files?

What packages do you use to handle command line options, settings and config files?

I'm looking for something that reads user-defined options from the command line and/or from config files.

The options (settings) should be dividable into different groups, so that I can pass different (subsets of) options to different objects in my code.

I know of boost::program_options, but I can't quite get used to the API. Are there light-weight alternatives?

(BTW, do you ever use a global options object in your code that can be read from anywhere? Or would you consider that evil?)

like image 636
Frank Avatar asked Jun 13 '09 04:06

Frank


1 Answers

At Google, we use gflags. It doesn't do configuration files, but for flags, it's a lot less painful than using getopt.

#include <gflags/gflags.h>
DEFINE_string(server, "foo", "What server to connect to");
int main(int argc, char* argv[]) {
    google::ParseCommandLineFlags(&argc, &argv, true);
    if (!server.empty()) {
        Connect(server);
    }
}

You put the DEFINE_foo at the top of the file that needs to know the value of the flag. If other files also need to know the value, you use DECLARE_foo in them. There's also pretty good support for testing, so unit tests can set different flags independently.

like image 77
albertb Avatar answered Oct 19 '22 23:10

albertb