How do you handle command line options and config files?

Frank picture Frank · Jun 13, 2009 · Viewed 7k times · Source

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?)

Answer

albertb picture albertb · Jun 13, 2009

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.