如何在Bison中将头文件放到.tab.h中?

时间:2017-12-09 07:32:47

标签: c++ compiler-construction bison

我写了野牛代码标题:

%{
#include "foo.h"
%}

我定义了一个名为' Foo'在标题中。我想在Bison中将它用作令牌类型。

%define api.value.type union
%token <Foo*> bar

然后我使用-d选项生成bison.tab.h文件。

bison -d bison.y

#include foo.h中没有bison.tab.h,它使用struct Foo来定义联合YYSTYPE。

//bison.tab.h
union YYSTPE {
    Foo* bar;
    ...
};

编译此程序时导致错误:error: ‘Foo’ does not name a type

有没有办法在bison.tab.h或本案的其他解决方案中包含头文件?

2 个答案:

答案 0 :(得分:5)

对于应出现在.c和.h文件中的包含(在%union的定义之前),您应该使用%code requires { ... }%{ ... }仅在.c文件中插入代码。

有关各种%code选项的详细信息,请查看"Prologue Alternatives" chapter of the Bison docs

答案 1 :(得分:0)

我需要使用 2.3 bison 版本,它没有 %code 指令,所以我只是添加了一个命令,在编译程序时将我的包含插入到 bison 输出头的顶部

echo #include \"my_include.hpp\" | cat - ${BISON_HEADER_OUTPUT} > tmp && mv tmp ${BISON_HEADER_OUTPUT}