getopt_long

"getopt"は一文字だけのオプションでしたが,
"getopt_long"はロングオプションを対応させることができます.

#include <unistd.h>
#include <getopt.h>

int getopt_long(int argc, char * const argv[],
    const char *optstring,
    const struct option *longopts, int *longindex);

int getopt_long_only(int argc, char * const argv[],
    const char *optstring,
    const struct option *longopts, int *longindex);


getopt_long Example

/* long_option.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>

void print_help(void);
void plus(void);

struct option long_options[] = {
    {"help",  no_argument, 0, 'h'},
    {"math",  no_argument, 0, 'm'},
    {0, 0, 0, 0},
};

int main(int argc, char **argv)
{
    int opt, opt_index = 0;
    int help_flag = 0;
    int math_flag = 0;

    if(argc < 2)
        print_help();

    while((opt = getopt_long(argc, argv, "hma:", long_options, &opt_index)) != EOF) {
        switch(opt) {
            case 'h':
                help_flag = 1;
                break;
            case 'm':
                math_flag = 1;
                break;
            case '?':
                help_flag = 1;
                break;
            default:
                help_flag = 1;
                break;
        }
    }

    if(help_flag)
        print_help();

    else
        if(math_flag)
            plus();

    return 0;
}

void print_help(void) {
    printf("Usage: ./long_opt [OPTION]\n");
    printf("-m, --math : 加算\n");
    printf("-h, --help : ヘルプを表示\n");
    exit(EXIT_SUCCESS);
}

void plus(void) {
    int na, nb, nc;
    char tmp[32];

    printf("Number A : ");
    fgets(tmp, 32, stdin);
    na = atoi(tmp);

    printf("Number B : ");
    fgets(tmp, 32, stdin);
    nb = atoi(tmp);

    nc = na + nb;

    printf("%d + %d = %d\n", na ,nb, nc);
}
下記の部分がプログラムのメイン
加算する関数とかあるけどぶっちゃけなんでもいい
struct option long_options[] = {
    {"help",  no_argument, 0, 'h'},
    {"math",  no_argument, 0, 'm'},
    {0, 0, 0, 0},
};

...

while((opt = getopt_long(argc, argv, "hma:", long_options, &opt_index)) != EOF) {
    switch(opt) {
    case 'h':
        help_flag = 1;
        break;
        
        ...
    }
}
"getopt_long"関数の第4引数に"long_options"構造体を参照しています.
構造体の第1変数は(char)型の変数, オプションの名前
    第2変数は(int)型の変数, "argment"を必要とするかどうか.
    第3変数は(int)*型の変数, ロングオプションに対する結果の返し方の指定.
    第4変数は(int)型の変数, 返り値, またはflagがポイントする変数へロードされる値

内容はほぼ"getopt"と変わらない. ロングオプションをつけたい場合にのみ使用してください.



実行例

$ ./long --math
Number A : 3
Number B : 4
3 + 4 = 7
$ ./long --help
Usage: ./long_opt [OPTION]
-m, --math : 加算
-h, --help : ヘルプを表示