C++: String and unions bison

bison, c++, string, unions

Solution

The problem is that the code in the `%{`...`%}` is only included the `y.tab.c` file generated by bison. It in NOT included in the `y.tab.h` file. The `%union` code, on the other hand, IS included in `y.tab.h` (it's part of the `YYSTYPE` definition). So if your `%union` depends on other declarations, simply putting those declarations (or an `#include`) in `%{`...`%}` won't always work.

Instead, you need to manually insure that those declarations always occur before you `#include "y.tab.h"` in any other file -- anywhere you have `#include "y.tab.h"` make sure you have `#include <string>` (and the `using` if you really want that) before the `#include "y.tab.h"` line. Putting it all in another header file you include is a good option.

Alternately, with bison (but not yacc), you can use `%code requires {`...`}` in the first section of the `.y` file. Anything in such a block will be copied verbatim into both the `y.tab.h` and `y.tab.c` files.

Problem

I am building a compiler in flex and bison. The thing is that using `char *` is giving a lot of problems so I'm trying to migrate everything to `string`. The only problem left is that there is a `union` with strings. I know that this is not a standard, but by using pointers there should be no problem. Relevant code: ``` #include <string> using namespace std; //-- SYMBOL SEMANTIC VALUES ----------------------------- %union { struct lc{ string * code; string * start; string * verdadero; string * falso; string * next; }code; } ``` The weird thing is the error I'm receiving: ``` file.ypp:39:6: error: ‘string’ does not name a type string * start; file.ypp:40:6: error: ‘string’ does not name a type string * verdadero; file.ypp:41:6: error: ‘string’ does not name a type string * falso; file.ypp:42:6: error: ‘string’ does not name a type string * next; ``` Edit: Forgot to mention that using `std::string` inside the `union` has the same problem

Original source

Related problems