What is the best practice for creating a unix/linux command-line tool in C/C++? What is the best practice for creating a unix/linux command-line tool in C/C++? linux linux

What is the best practice for creating a unix/linux command-line tool in C/C++?


getopt_long() is what you're looking for, here's an example of the simplest usage:

   static const struct option opts[] = {        {"version",   no_argument,    0, 'v'},        {"help",      no_argument,    0, 'h'},        {"message", required_argument, 0, 'm'},        /* And so on */        {0,      0,                   0,  0 }   /* Sentiel */    };    int optidx;    char c;    /* <option> and a ':' means it's marked as required_argument, make sure to do that.     * or optional_argument if it's optional.     * You can pass NULL as the last argument if it's not needed.  */    while ((c = getopt_long(argc, argv, "vhm:", opts, &optidx)) != -1) {        switch (c) {            case 'v': print_version(); break;            case 'h': help(argv[0]); break;            case 'm': printf("%s\n", optarg); break;            case '?': help(argv[0]); return 1;                /* getopt already thrown an error */            default:                if (optopt == 'c')                    fprintf(stderr, "Option -%c requires an argument.\n",                        optopt);                else if (isprint(optopt))                    fprintf(stderr, "Unknown option -%c.\n", optopt);                else                    fprintf(stderr, "Unknown option character '\\x%x'.\n",                        optopt);               return 1;        }    }    /* Loop through other arguments ("leftovers").  */    while (optind < argc) {        /* whatever */;        ++optind;    }