2017-11-02 4 views
0

次は、http://www.gnu.orgのコード例です。確かにほとんどの人が見るように、それはgetoptであり、私は変数の宣言について質問しています。なぜタイプや何も書かれていないのですgetoptのopterr宣言

opterr = 0; 

これまで私はこれまで見たことがありません。

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

int 
main (int argc, char **argv) 
{ 
    int aflag = 0; 
    int bflag = 0; 
    char *cvalue = NULL; 
    int index; 
    int c; 

    opterr = 0; 


    while ((c = getopt (argc, argv, "abc:")) != -1) 
    switch (c) 
     { 
     case 'a': 
     aflag = 1; 
     break; 
     case 'b': 
     bflag = 1; 
     break; 
     case 'c': 
     cvalue = optarg; 
     break; 
     case '?': 
     if (optopt == 'c') 
      fprintf (stderr, "Option -%c requires an argument.\n", optopt); 
     else if (isprint (optopt)) 
      fprintf (stderr, "Unknown option `-%c'.\n", optopt); 
     else 
      fprintf (stderr, 
        "Unknown option character `\\x%x'.\n", 
        optopt); 
     return 1; 
     default: 
     abort(); 
     } 
    printf ("aflag = %d, bflag = %d, cvalue = %s\n", 
      aflag, bflag, cvalue); 

    for (index = optind; index < argc; index++) 
    printf ("Non-option argument %s\n", argv[index]); 
    return 0; 
} 
+1

「optarg」がどこから来るのか尋ねるのは面白いです。 – user0042

+0

あなたが選んだIDEは、関数 "Show Declaration"(または同様のもの)をサポートしているかもしれません。たとえば、Eclipse CDTでは、ボタン "F3"ですが、変数を右クリックしてこの関数を手動で選択することもできます。 – xMutzelx

答えて

2

opterr(3)unistd.h内でextern変数として宣言されています

extern int optind, opterr, optopt; 

だから、この場合、異なる翻訳単位、標準のCライブラリで定義されたグローバル変数です。

0にそれを設定した理由は、manページで説明されています

getopt()は、オプション文字を認識しない場合、それは、stderrにエラーメッセージを出力optoptに文字を格納し、'?'を返します。 。呼び出し側プログラムは、opterrを0に設定することにより、エラーメッセージを防ぐことができます。