使用yyparse()进行编译时遇到的困难(g ++,bison,flex);

pid*_*row 4 c++ compiler-construction g++ bison flex-lexer

编译我的代码有问题:

柔性:

%{
#include "lista4.tab.hpp"
#include <stdlib.h>
extern int yylex();
%}
%%
"=" {return EQ;}
"!="    {return NE;}
"<" {return LT;}
">" {return GT;}
":="    {return ASSIGN;}
";" {return SEMICOLON;}
"IF"    {return IF;}
"THEN"{return THEN;}

"END" {return END;}
[_a-z]+ {yylval.text = strdup(yytext); return IDENTIFIER;}
[ \t]+
[0-9]+          {
                yylval.var = atoi (yytext);
                return NUMBER;
                }
[-+/^*'%'()]    {
                return *yytext;
                }
\n              return RESULT;
%%
Run Code Online (Sandbox Code Playgroud)

野牛:

%{
  extern "C"
  {
    int yyparse();
    int yylex(void);
    void yyerror(char *s){}
    int yywrap(void){return 1;}
  }

  #include <iostream>
  #include <vector>
  #include <string>
  #include <stdlib.h>
  #include <map>

  using namespace std;

  vector <string> instructions;
  map <> vars;
%}

%union{
  char* text;
  int var;
}


%token EQ
%token NE
%token ASSIGN
%token SEMICOLON
%token IF
%token THEN
%token <text> IDENTIFIER
%token <var> NUMBER
%token <var> RESULT

%left '+' '-'
%left '*' '/' '%'
%right '^'

%%

exp: NUMBER
| IDENTIFIER
| IDENTIFIER "+" IDENTIFIER
| IDENTIFIER "-" IDENTIFIER
;
%%

int main(void){
  yyparse();
} 
Run Code Online (Sandbox Code Playgroud)

和bash脚本:

#!/bin/bash
clear
rm launcher lex.yy.cpp *.tab.cpp *.tab.hpp
bison  -d -o lista4.tab.cpp *.y
flex -o lex.yy.cpp *.l
g++ -o launcher *.cpp -lfl
Run Code Online (Sandbox Code Playgroud)

我在这里只发布了代码中最重要的部分,因为这里没有其他部分.无论如何,如果有人想看到整个代码,我在这里粘贴:http://pastebin.com/1rS2FBJj.但它有点大,需要更多的地方.

当我尝试将所有文​​件编译成*.c文件然后通过gcc编译时,一切都很好.但是当我将编译器切换到g ++并将文件切换到cpp时,我收到此错误:

lista4.tab.cpp: In function ‘int yyparse()’:
lista4.tab.cpp:1397: warning: deprecated conversion from string constant to ‘char*’
lista4.tab.cpp:1540: warning: deprecated conversion from string constant to ‘char*’
/tmp/ccdqpQVx.o: In function `yyparse':
lista4.tab.cpp:(.text+0x252): undefined reference to `yylex'
collect2: ld returned 1 exit status

任何人都可以给我一个提示如何解决它?

Rob*_*edy 11

在Flex文件中,您声明:

extern int yylex();
Run Code Online (Sandbox Code Playgroud)

当编译为C++时,它声明了一个具有C++链接的函数.在您的Bison文件中,您声明:

extern "C" {
  int yylex();
}
Run Code Online (Sandbox Code Playgroud)

这给了它C连接.它们有两个不同的功能.您定义了C++版本(或者更确切地说,Flex为您定义了它),但是您声明了C版本,而C版本是编译器认为您尝试调用的版本(在Bison生成的代码中).链接器看到使用了C版本,但找不到定义.

选择一个链接并始终如一地使用它.(我选择C++,因为它允许完全从代码中省略"extern"内容.)