写在前面:
对于可选参数一定要使用以下两种方法标明其值 –wValue 或--who==Value 而不能是 --who Value,
而对于必填参数则可以使用-lValue 或 --love Value或--love=Value,
这并不是bug.
//============================================================================ // Name : TestOpt.cpp // Author : yangyh // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <getopt.h> using namespace std; int version; struct option longopts[] = { { "version", no_argument, &version, 'v' }, { "name", no_argument, NULL, 'n' }, { "love", required_argument, NULL,'l' }, { "who",optional_argument,NULL,'w'}, { 0, 0, 0, 0 } }; int main(int argc, char *argv[]) { int c; while ((c = getopt_long(argc, argv, "vl:w::", longopts, NULL)) != -1) { switch (c) { case 'l': printf("love = %s!\n", optarg); break; case 0: // printf("getopt_long()设置变量 : version = %c\n", version); break; case 'v': printf("version..\n"); break;
case 'w': printf("who = %s\n",optarg); break; } } return 0; }