使用野牛制作可执行文件但错误

时间:2011-11-03 21:55:20

标签: bison flex-lexer

我跟着Flex and Bison tutorial学习flex&野牛, 但我被困住了。当我编译时 “g ++ snazzle.tab.c lex.yy.c -lfl -o snazzle”, 我收到这些错误消息:

 snazzle.tab.c: In function ‘int yyparse()’:
 snazzle.tab.c:1403: warning: deprecated conversion from string constant to ‘char*’
 snazzle.tab.c:1546: warning: deprecated conversion from string constant to ‘char*’
 /tmp/ccFyBCBm.o: In function `yyparse':
 snazzle.tab.c:(.text+0x1e0): undefined reference to `yylex'
 collect2: ld returned 1 exit status

我的环境是ubuntu 10.04 野牛2.4.1 flex 2.5.35

我仍然找不到问题。首先我用“bison -o snazzle.y”编译,然后分别生成两个snazzle.tab.c和snazzle.tab.h。最后我用“g ++ snazzle.tab.c lex.yy.c -lfl -o snazzle”编译。我的代码如下:

snazzle.l
%{
#include <cstdio>
#include <iostream>
using namespace std;
#include "snazzle.tab.h" 
%}
%%
[ \t]          ;
[0-9]+\.[0-9]+ { yylval.fval = atof(yytext); return FLOAT; }
[0-9]+         { yylval.ival = atoi(yytext); return INT; }
[a-zA-Z0-9]+   {
// we have to copy because we can't rely on yytext not changing underneath us:
yylval.sval = strdup(yytext);
return STRING;
}
.              ;
%%

snazzle.y
%{
#include <cstdio>
#include <iostream>
using namespace std;

extern "C" int yylex();
extern "C" int yyparse();
extern "C" FILE *yyin;

void yyerror(char *s);
%}

%union {
int ival;
float fval;
char *sval;
}

%token <ival> INT
%token <fval> FLOAT
%token <sval> STRING

%%

snazzle:
INT snazzle      { cout << "bison found an int: " << $1 << endl; }
| FLOAT snazzle  { cout << "bison found a float: " << $1 << endl; }
| STRING snazzle { cout << "bison found a string: " << $1 << endl; }
| INT            { cout << "bison found an int: " << $1 << endl; }
| FLOAT          { cout << "bison found a float: " << $1 << endl; }
| STRING         { cout << "bison found a string: " << $1 << endl; }
;
%%

main() {
// open a file handle to a particular file:
FILE *myfile = fopen("a.snazzle.file", "r");
// make sure it is valid:
if (!myfile) {
    cout << "I can't open a.snazzle.file!" << endl;
    return -1;
}
// set flex to read from it instead of defaulting to STDIN:
yyin = myfile;

// parse through the input until there is no more:
do {
    yyparse();
} while (!feof(yyin));
}

void yyerror(char *s) {
cout << "EEK, parse error!  Message: " << s << endl;
// might as well halt now:
exit(-1);
}

1 个答案:

答案 0 :(得分:0)

您在一个源文件中定义了一堆事物extern "C"但在另一个源文件中没有定义 - 要么删除"C",要么将这些声明复制到.l文件中。实际上最好把所有这些声明放到一个.h文件中,你到处都是#include。这与flex / bison没有任何关系,只是一般的C / C ++问题。

相关问题