当有错误的命令行参数时,如何使 getopt_long() 不打印任何内容?

How to make getopt_long() print nothing when there is error command-line arguments?

我有一个程序使用 getopt_get() 来解析命令行参数。 我的代码是这样的:

int opt;
int optionIndex;
static struct option longOptions[] = {
    {"help", no_argument, NULL, 'h'},
    {"test", no_argument, NULL, 't'},
    {0, 0, 0, 0}
}; 
while ((opt = getopt_long(argc, argv, "ht", longOptions, &optionIndex)) != -1) {
    switch (opt) {
        case 'h':
            help();
            return 0;
            break;
        case 't':
            init();
            test();
            return 0;
            break;
        case '?':
            help();
            return 1;
            break;
        default:
            printf("default.\n");
    }   

当我将正确的命令行参数传递给程序时,它运行良好。 但是当错误的参数传递给程序时,它会打印出这样烦人和多余的单词。

例如,我向程序

传递了错误的参数'q'
$ ./program -q
./program: invalid option -- 'q'
Usage: -h -t

当有错误的参数时,我只想要它运行我的函数help()而不打印任何字。

./program: invalid option -- 'q'

我怎样才能停止 getopt_long 打印这个烦人的词而不打印任何东西?

阅读 fine manual...

If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in optopt, and returns '?'. The calling program may prevent the error message by setting opterr to 0.

因此,在调用 getopt_long 之前尝试此操作:

opterr = 0;