【问题标题】:DOM Parser Using Flex and Bison使用 Flex 和 Bison 的 DOM 解析器
【发布时间】:2013-03-17 02:09:17
【问题描述】:

我正在开发一个创建 DOM 解析器的项目。在初始阶段,我只是想弄清楚给定文件中有多少标签。假设我有一个 XML 文件,其内容有点像这样:<abc>this is test file</abc> ,为此我只想解析<abc></abc>这两个标签。为此,我使用 Flex 和 Bison 编写语法,以便每当出现这种语法时,我都会执行我的代码。这是我的 Bison 代码:

%{
    #include <stdio.h>
    #include <conio.h>
    int yylex();
    int yyparse();
    FILE *yyin;
    int yylineno;
    void yyerror(const char*);
%}

%token START_TAG END_TAG 

%%
tag:
    sTag
    | eTag
    ;
sTag:
    START_TAG {printf("start tag encountered");}
    ;
eTag:
    END_TAG
    ;
%%
int main(){
    FILE *myFile;
    myFile = fopen("G:\\MCA-2\\project\\09-03-2013\\demo.txt","r");
    if(!myFile){
        printf("error opening file");
    }
    yyin = myFile;
    do{
        yyparse();
    } while(!feof(yyin));
    fclose(myFile);
    return 0;
}

这是我的 Flex 代码:

%{
    #include "xml.tab.h"
    #define YY_DECL extern "C" int yylex()
%}

%option noyywrap
%option yylineno
alpha [a-zA-Z]
digit [0-9]
%%
[ \t] {}
[ \n] {}
{alpha}({alpha}|{digit})* return START_TAG;
%%

当我试图编译这个时,我得到一个这样的错误:

lex.yy.c : 529:1: 错误:预期标识符或字符串常量前的 '('。

谁能告诉我我犯了什么错误?

【问题讨论】:

  • 你如何编译“this”(我想你的意思是lex.yy.c)声明extern "C"...只在C++中有效,在C中无效,通常file.c会被编译为C。
  • 我正在以以下方式编译:gcc lex.yy.c xml.tab.c -o xml.exe。我删除了 extern "C" 只是为了尝试变化,但后来错误没有发生。
  • 因此您将其编译为 C 程序。在这种情况下,完全摆脱#define YY_DECL 行,因为默认声明就可以了。每次更改 flex 文件时不要忘记运行 flex 以重新生成 lex.yy.c
  • 感谢 rici 解决了我的问题。我得到了我的解决方案。我删除了#define YY_DECL,问题就解决了。你能解释一下到底是什么问题吗?
  • 见我第一条评论的第二句。

标签: bison flex-lexer


【解决方案1】:

(问题已在 cmets 中得到解答;请参阅:Question with no answers, but issue solved in the comments (or extended in chat)

@rici 提供了答案。由于 flex 正在为 gcc 编译器生成 C 代码完全摆脱 #define YY_DECL 行,因为默认声明会很好。每次更改 flex 文件时不要忘记运行 flex 以重新生成 lex.yy.c。声明 extern "C"... 仅在 C++ 中有效,在 C 中无效,并且通常 file.c 将被编译为 C。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多