gpt4 book ai didi

C++:字符串和 union Bison

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:20:06 25 4
gpt4 key购买 nike

我正在用 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;
}

奇怪的是我收到的错误:

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;

编辑:忘记提到在 union 中使用 std::string 有同样的问题

最佳答案

问题是 %{ 中的代码... %}仅包含 y.tab.c Bison 生成的文件。它不包含在 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 { ... }.y 的第一部分文件。此类 block 中的任何内容都将被逐字复制到 both y.tab.h 中和 y.tab.c文件。

关于C++:字符串和 union Bison ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23633928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com