kna*_*arf 4 c++ bison flex-lexer
首先,我对Bison和Flex都很陌生.我知道这些工具是为C语言设计的,我觉得我的所有问题都来自于在C++中使用它们.我不确定我是以正确的方式做到的.
代码在我的计算机上编译良好,但不在我的大学服务器上.我已将此问题隔离到此处.
在我的大学:
$ (g++ --version; bison --version; flex --version)|grep '[0-9]\.' g++ (Debian 4.4.5-8) 4.4.5 bison (GNU Bison) 2.4.1 flex 2.5.35
在家:
HOME $ (g++ --version; bison --version; flex --version)|grep '[0-9]\.' g++ (GCC) 4.7.1 20120721 (prerelease) bison (GNU Bison) 2.6.2 flex 2.5.37
我使用以下命令编译:
bison -d parse.y && flex lex.l && g++ main.cpp lex.yy.c parse.tab.c -lfl
正如我已经说过的,它在我的计算机上编译很好(没有警告),但我在服务器上得到了这个:
main.cpp: In function 'int main()': main.cpp:28: error: 'yyparse' was not declared in this scope
由于SO在括号方面存在一些问题,我还上传了一个tarball.
lex.l
%{
#include
#include "dict.hpp"
#include "parse.tab.h"
%}
%%
[0-9]+ yylval.num = atoi(yytext); return NUM;
[a-z]+ yylval.id = dict.id(yytext); return ID;
[:space:] ;
parse.y
%{
#include
#include "dict.hpp"
void yyerror (const char* e) {
puts(e);
}
int yylex ();
%}
%union{
uint id;
int num;
}
%token ID;
%token NUM;
%%
S : ID NUM S {
dict.set($1, $2);
}
|;
dict.hpp
#ifndef _DICT_HPP_
#define _DICT_HPP_
#include
#include
typedef std::pair dpair;
typedef unsigned int uint;
class Dict {
std::vector tab;
public:
uint id(char* s);
void set(uint i, int v);
void print();
};
extern Dict dict;
#endif /* _DICT_HPP_ */
main.cpp中
#include <vector>
#include <string>
#include <cstdio>
#include "dict.hpp"
#include "parse.tab.h"
Dict dict;
uint Dict::id (char* s) {
for(uint i = 0; i < tab.size(); i++)
if(tab[i].first == s)
return i;
tab.push_back(dpair(std::string(s), tab.size()));
return tab.size()-1;
}
void Dict::set (uint i, int v) {
tab[i].second = v;
}
void Dict::print () {
for(uint i = 0; i < tab.size(); i++)
printf("%20s = %d\n", tab[i].first.c_str(), tab[i].second);
}
int main ()
{
yyparse();
dict.print();
}
Run Code Online (Sandbox Code Playgroud)
OFFTOPIC:flex不是GNU软件.
你可以添加
extern "C" int yyparse (void);
Run Code Online (Sandbox Code Playgroud)
在您的main.cpp文件中(也可能在parser.y)或某些常见的#include-d头文件中.
你真的应该g++ -Wall -g用来编译你的代码.
| 归档时间: |
|
| 查看次数: |
5754 次 |
| 最近记录: |