10

I wrote bison code header:

%{
#include "foo.h"
%}

And I defined a struct named 'Foo' in header. I'd like to use it as token type in Bison.

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

Then I use -d option to generate bison.tab.h file.

bison -d bison.y

But there is no #include foo.h in bison.tab.h, and it use struct Foo to define the union YYSTYPE.

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

It caused error when compile this program: error: ‘Foo’ does not name a type

Is there a way to include header file in bison.tab.h or another solution of this case?

sepp2k
  • 363,768
  • 54
  • 674
  • 675
syxbyi
  • 141
  • 1
  • 6
  • can you share your bison.y ? – Ahmed Masud Dec 09 '17 at 07:43
  • What you put between `%{` and `%}` is not processed by Bison, it is copied straight into the generated C (or C++) source file. You can not put Bison-specific statements in a header file that way. – Some programmer dude Dec 09 '17 at 07:44
  • "*But there is no #include foo.h in bison.tab.h*" <= please show (at least the top of) your `foo.h` and `bison.y`. Because from what's currently given, this is how it's done. – dhke Dec 09 '17 at 07:46

2 Answers2

13

For includes that should appear in both the .c and the .h file (before the definition for the %union), you should use %code requires { ... }. %{ ... } inserts code in the .c file only.

For more information on the various %code options, you can look at the "Prologue Alternatives" chapter of the Bison docs.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
0

I needed to use 2.3 bison version, which doesn't have %code directive, so I just added a command which insert my include into top of bison output header, when I compile program

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