0
votes

I am working on a project to create a DOM parser. At the initial stage I am simply trying to figure out how many tags are there in the given file. Let's say I have an XML file whose content is somewhat like this : <abc>this is test file</abc> , for this I only want to parse the two tags <abc> and </abc>. For this happen I am using Flex and Bison to write a grammar so that whenever this grammar occurs I execute my code. This is my Bison code :

%{
    #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;
}

And this is my Flex code :

%{
    #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;
%%

When I am trying to compile this I am getting an error like this :

lex.yy.c : 529:1: error: expected identifier or '(' before string constant.

Can anyone tell me what is the mistake I am making?

1
How are you compiling "this" (I think you mean lex.yy.c) The declaration extern "C"... is only valid in C++, not in C, and normally file.c would be compiled as C.rici
I am compiling in following manner : gcc lex.yy.c xml.tab.c -o xml.exe. I removed extern "C" just to try variation but then to the error didnt go.iammurtaza
So you're compiling it as a C program. In that case, get rid of the #define YY_DECL line altogether, since the default declaration will be fine. Don't forget to run flex every time you change your flex file, to regenerate lex.yy.c.rici
Thank you rici for solving my problem. I got my solution. I removed #define YY_DECL and the problem got solved. Can you explain what was the problem actually?iammurtaza
See the second sentence of my first comment.rici

1 Answers

0
votes

(Question answered in the comments; see: Question with no answers, but issue solved in the comments (or extended in chat) )

@rici Provided the answer. As flex is generating C code for the gcc compiler get rid of the #define YY_DECL line altogether, since the default declaration will be fine. Don't forget to run flex every time you change your flex file, to regenerate lex.yy.c. The declaration extern "C"... is only valid in C++, not in C, and normally file.c would be compiled as C.