c++ - yyparse() 未在 Bison/Flex C++ 项目中仅针对某些版本的 gcc/bison/flex 声明

标签 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

At home:

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

I use the following command to compile: bison -d parse.y && flex lex.l && g++ main.cpp lex.yy.c parse.tab.c -lfl

As I already said, it compiles fine (no warnings) on my computer but I get this on the server:

main.cpp: In function 'int main()':
main.cpp:28: error: 'yyparse' was not declared in this scope

Since SO has some problem with brackets, I've also uploaded a 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();
}

题外话:flex is not a GNU software .

最佳答案

你可以添加

 extern "C" int yyparse (void);

在您的 main.cpp 文件中(可能也在 parser.y 中)或在一些常见的 #include-d 头文件中。

你真的应该使用 g++ -Wall -g 来编译你的代码。

关于c++ - yyparse() 未在 Bison/Flex C++ 项目中仅针对某些版本的 gcc/bison/flex 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12768411/

相关文章:

c++ - 将值从 flex 传递给 bison

thread-safety - 使用 Flex 编写可重入词法分析器

c++ void *到函数的参数

c++ - 为什么 C++20 不支持 "void f(Concept const auto&)"?

c - 在 bison 中使用 $2 时出现段错误

c++ - Bison 中哈希查找的问题

c - 使用此语法在 flex/bison 中获取语法错误

c++ - Windows时区写入注册表是否可靠?

c++ - 带有模板参数的 make_tuple 不编译

c - YACC语法减少/减少冲突