getopt(3)是如何工作的,什么是'extern'变量optarg?

时间:2014-04-30 23:55:29

标签: c unix getopt

我正在尝试学习如何接受命令行参数和标记后的伴随数据,即

myprogram -sampleflag datahere

我的代码到目前为止。 getopt()将数据抛出到变量 c 中,显然您可以从调用它的函数外部访问 optarg 。这怎么可能?根据手册页,我的代码应该工作!但是,如您所见,输出为(null)。

我的代码:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    opterr = 0;
    char* cvalue = NULL;
    int c;
    char* optarg = hello;

while((c = getopt(argc, argv, "ps")) != -1){
    switch(c){
        case 'p':
            cvalue = optarg;
            printf("cvalue is : %s\n", cvalue );
            break;
        }
    }
}

我的输出:($ myprogram -p test)

cvalue is : (null)

1 个答案:

答案 0 :(得分:4)

来自the manual

  

此字符串中的选项字符后面可以跟冒号(':'),表示它需要一个必需的参数。

因此,在您的情况下,您的选项字符串应为"p:s"而不是"ps"