包括由 flex 和 bison 生成的代码
Include generated code by flex and bison
我在C++中使用Flex和Bison。我正在学习使用这些工具,最好的开始方法是执行一个简单的计算器。从我的 calc.y 和 calc.l 文件生成应用程序(可执行文件)后,我可以运行 .exe 文件并使用它,但现在我想将其包含在文件 c ++ 中以在我的应用程序中使用它,但我不能。我认为这是我的错,因为我包含错误的生成的文件或生成要导入的不良代码。
主.cpp
#include <iostream>
extern "C" {
#include "y.tab.h"
}
int main ( int argc, char *argv[] ) {
yyparse();
printf(elementos);
return 0;
}
计算
%{
#include "y.tab.h"
#include <stdlib.h>
void yyerror(char *);
%}
%%
[0-9]+ {
yylval = atoi(yytext);
return INTEGER;
}
[-+()n] {
return *yytext;
}
[ t] ;
. {
yyerror("Invalid character.");
}
%%
int yywrap(void) {
return 1;
}
计算
%{
#include <stdio.h>
int yylex(void);
void yyerror(char *);
int sym[26];
int elementos = 0;
%}
%token INTEGER VARIABLE
%left '+' '-'
%left '*' '/'
%%
program:
program expr 'n' { printf("%dn", $2 ); }
|
;
statement:
expr { printf("%dn", $1); }
| VARIABLE '=' expr { sym[$1] = $3; }
;
expr:
INTEGER { $$ = $1; }
| expr '+' expr { $$ = $1 + $3; elementos = elementos + 1;}
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
| '(' expr ')' { $$ = $2; }
;
%%
void yyerror(char *s) {
fprintf(stderr, "%sn", s);
}
int main(void) {
yyparse();
return 0;
}
y.tab.h 由野牛生成。当我尝试编译main时.cpp我收到一个错误:
命令: gcc main.cpp -o main.exe
结果:main.cpp: In function 'int main(int, char**)':
main.cpp:8:10: error: 'yyparse' was not declared in this scope
main.cpp:9:9: error: 'elementos' was not declared in this scope
我该如何解决它?
我在 Windows 4.7.2 上使用 gcc 版本、bison 2.4.1 和 2.5.4 8.1。
谢谢!
编辑:
y.tab.h 文件是:
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
INTEGER = 258,
VARIABLE = 259
};
#endif
/* Tokens. */
#define INTEGER 258
#define VARIABLE 259
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef int YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
#endif
extern YYSTYPE yylval;
没有"elementos"变量,但是查看生成的y.tab.c文件,我发现有定义的!
您有许多问题:
-
Bison和Flex生成C代码,然后你需要编译这些代码并与你的程序链接。您的问题没有表明您已执行此操作。
-
如果您希望能够在 main.cpp 文件中使用 elementos 变量,则需要声明它。它可能在其他地方定义,但编译器在编译 main.cpp 时不知道这一点。在外部"C"部分内添加此行:
extern int elementos;
-
您有两个不同的主要功能。
-
在main.cpp中,你 #include iostream,但随后使用stdio的printf。
-
对printf的调用是错误的。它需要一个格式字符串。
-
Bison显示了几个警告,如果您希望程序正常工作,您可能需要阅读并执行一些操作。
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- G++ 在编译我的 flex 和 bison 代码时无法识别我的 c++ 类
- 我如何控制bison将c++代码放在哪里
- 包括由 flex 和 bison 生成的代码