getopt(3) Library Functions Manual getopt(3) getopt, optarg, optind, opterr, optopt - (libc -lc) #include int getopt(int argc, char *argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; glibc ( feature_test_macros(7)): getopt(): _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE getopt() . argc argv main() . argv '-' ( "-" "--") . ( '-' ) . getopt() . optind argv. 1. 1 argv . getopt() optind nextchar getopt() argv. getopt() -1. optind argv argv . optstring . ascii(7) ( isgraph(3) ) '-' ':' ';'. getopt() argv argv optarg. argv ( "-oarg") optarg optarg . GNU. optstring W -W foo --foo. ( -W POSIX.2 .) GNU glibc 2. getopt() argv . . optstring '+' POSIXLY_CORRECT . '+' optstring . POSIXLY_CORRECT optstring '+'. optstring '-' argv 1. ( argv .) "--" . getopt() : (1) optstring (2) ( ). : o getopt() optopt '?' . o opterr getopt() . '?'. ( opterr .) o ( '+' '-' ) optstring (':') getopt() . ':' '?' . . getopt() . getopt() -1. getopt() optstring '?' . getopt() optstring: ':' ':' '?'. POSIXLY_CORRECT . attributes(7). +----------------------+------------------------------------+----------+ | | | | +----------------------+------------------------------------+----------+ |getopt() | | | | | | | | | | | | | | | | | | (MT-Unsafe) | | | | :getopt | | | | env | +----------------------+------------------------------------+----------+ POSIX argv const POSIXLY_CORRECT. const . getopt() POSIX.1-2008. '+' '-' optstring GNU. getopt() POSIX.1-2001 POSIX.2. getopt() . SUSv1 . POSIX.1-1996 (LEGACY). POSIX.1-2001 . glibc _PID_GNU_nonoption_argv_flags_ . GNU '+' '-' optstring POSIXLY_CORRECT getopt() optind 0 1. ( 0 POSIXLY_CORRECT GNU optstring.) ( ). optstring "1n:" prog -n -1 -n optarg "-1" -1 . getopt() getopt() : -n -t val . #include #include #include int main(int argc, char *argv[]) { int flags, opt; int nsecs, tfnd; nsecs = 0; tfnd = 0; flags = 0; while ((opt = getopt(argc, argv, "nt:")) != -1) { switch (opt) { case 'n': flags = 1; break; case 't': nsecs = atoi(optarg); tfnd = 1; break; default: /* '?' */ fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n", argv[0]); exit(EXIT_FAILURE); } } printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\n", flags, tfnd, nsecs, optind); if (optind >= argc) { fprintf(stderr, "Expected argument after options\n"); exit(EXIT_FAILURE); } printf("name argument = %s\n", argv[optind]); /* Other code omitted */ exit(EXIT_SUCCESS); } getopt(1) getopt_long(3) getopt_long_only(3) getsubopt(3) 3 . . : . 6.18 8 2026 getopt(3)