2017-09-25 69 views
2

我正在與詞法分析。爲此,我使用Flex並提取以下問題。函數'yylex':'變量'未聲明

work.l

int cnt = 0,num_lines=0,num_chars=0; // Problem here. 
%% 
[" "]+[a-zA-Z0-9]+  {++cnt;} 
\n {++num_lines; ++num_chars;} 
. {++num_chars;} 
%% 
int yywrap() 
{ 
    return 1; 
} 
int main() 
{ yyin = freopen("in.txt", "r", stdin); 
    yylex(); 
    printf("%d %d %d\n", cnt, num_lines,num_chars); 
    return 0; 
} 

然後,我用下面的命令,它正常工作,創造lex.yy.c

Rezwans的iMac:laqb-2 rezwan $彎曲work.l


然後,我用下面的命令。

Rezwans的iMac:laqb-2 rezwan $ GCC的lex.yy.c -Ob

並獲得以下error

work.l: In function ‘yylex’: 
work.l:3:4: error: ‘cnt’ undeclared (first use in this function); did you mean int’? 
[" "]+[a-zA-Z0-9]+ {++cnt;} 
    ^~~ 
    int 
work.l:3:4: note: each undeclared identifier is reported only once for each function it appears in 
work.l:4:4: error: ‘num_lines’ undeclared (first use in this function) 
\n {++num_lines; ++num_chars;} 
    ^~~~~~~~~ 
work.l:4:17: error: ‘num_chars’ undeclared (first use in this function); did you mean ‘num_lines’? 
\n {++num_lines; ++num_chars;} 
       ^~~~~~~~~ 
       num_lines 
work.l: In function ‘main’: 
work.l:15:23: error: ‘cnt’ undeclared (first use in this function); did you mean ‘int’? 
    return 0; 
        ^ 
         int 
work.l:15:28: error: ‘num_lines’ undeclared (first use in this function) 
    return 0; 
          ^  
work.l:15:38: error: ‘num_chars’ undeclared (first use in this function); did you mean ‘num_lines’? 
    return 0; 
            ^  
             num_lines 

我沒有得到上述error,如果我像這樣修改work.l文件。

int cnt = 0,num_lines=0,num_chars=0; // then work properly above command. 
%% 
[" "]+[a-zA-Z0-9]+  {++cnt;} 
\n {++num_lines; ++num_chars;} 
. {++num_chars;} 
%% 
int yywrap() 
{ 
    return 1; 
} 
int main() 
{ yyin = freopen("in.txt", "r", stdin); 
    yylex(); 
    printf("%d %d %d\n", cnt, num_lines,num_chars); 
    return 0; 
} 

也就是說,如果我這一行int cnt = 0,num_lines=0,num_chars=0;之前使用1 tab,它工作正常。

現在我有兩個問題:

  1. 這是行前int cnt = 0,num_lines=0,num_chars=0;配套使用1 tab?爲什麼?邏輯解釋。

  2. 是解決這個錯誤的另一種解決方案嗎?

+0

您是否閱讀過有關定義部分格式的文檔? – molbdnilo

+0

是啊@molbdnilo。但我找不到這樣的人。 –

回答

6

我不是很肯定的標籤問題,但有一種解釋是,如果你不把標籤,並在首節像寫:

int cnt = 0; 

然後注意的是,在第一部分你也可以寫「捷徑」,如:

Digit [0-9] 

這是一個定義是不是編寫所有的時間[0-9]表示數字是什麼數字正則表達式。

所以不使用標籤在第一列寫int cnt = 0;時就像定義關鍵字INT(這可能就是錯誤告訴你did you mean int’?)。所以選項卡是區分上述兩種情況的一種方式。

根據彎曲爲了寫C/C++,它需要在裏面代碼:%{ ... c/c++ code... %}所以你的例子:

%{ 
    int cnt = 0,num_lines=0,num_chars=0; 
%} 

所以我的事情最好的辦法是寫你%{ %}內的c代碼。

+1

非常感謝您的好解釋。 –