rfo*_*eck 5 c++ string bison unions
我正在flex和bison中构建一个编译器.问题是使用char *会带来很多问题,所以我试图将所有内容迁移到string.
剩下的唯一问题是有一个union字符串.我知道这不是标准,但通过使用指针应该没有问题.
相关代码:
#include <string>
using namespace std;
//-- SYMBOL SEMANTIC VALUES -----------------------------
%union {
struct lc{
string * code;
string * start;
string * verdadero;
string * falso;
string * next;
}code;
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是我收到的错误:
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;
Run Code Online (Sandbox Code Playgroud)
编辑:忘了提到std::string在里面使用 union有同样的问题
问题是,在代码%{...%}只包括y.tab.c野牛生成的文件。它不包含在y.tab.h文件中。该%union代码,而另一方面,包括在y.tab.h(它的一部分的YYSTYPE定义)。因此,如果您%union依赖于其他声明,只需将这些声明(或#include)放入%{...%}并不总是有效。
相反,你需要手动确保这些声明总是发生之前,你#include "y.tab.h"在其他任何文件-任何地方,你必须#include "y.tab.h"让
确保您有#include <string>(和using如果你真的想要的)的前#include "y.tab.h"行。将其全部放在您包含的另一个头文件中是一个不错的选择。
或者,对于 bison(但不是 yacc),您可以在文件的第一部分使用%code requires {...。任何这样的块将被逐字复制到两者的和文件。}.yy.tab.hy.tab.c