我正在使用 C++ 中的 Flex 和 Bison 进行工作。我正在学习使用这些工具,最好的开始方法是执行一个简单的计算器。从我的 calc.y 和 calc.l 文件生成应用程序(可执行文件)后,我可以运行 .exe 文件并使用它,但现在我想将它包含在文件 c++ 中以在我的应用程序中使用它,但是我不能。我认为这是我的错,因为我包含了错误的生成文件或生成了错误的代码来导入。
main.cpp
#include <iostream>
extern "C" {
#include "y.tab.h"
}
int main ( int argc, char *argv[] ) {
yyparse();
printf(elementos);
return 0;
}
计算.l
%{
#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;
}
calc.y
%{
#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("%d\n", $2 ); }
|
;
statement:
expr { printf("%d\n", $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, "%s\n", s);
}
int main(void) {
yyparse();
return 0;
}
y.tab.h是由bison生成的。当我尝试编译 main.cpp 时,出现错误:
命令:gcc main.cpp -o main.exe
结果:main.cpp:在函数“int main(int, char**)”中:
main.cpp:8:10: 错误:'yyparse' 未在此范围内声明
main.cpp:9:9: 错误:'elementos' 未在此范围内声明
如何修复它?
我在 Windows 8.1 上使用 gcc 版本 4.7.2、bison 2.4.1 和 2.5.4。
谢谢!
编辑:
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 时并不知道这一点。在 extern "C"部分添加此行:
extern int elementos;
您有两个不同的主要功能。
在 main.cpp 中,#include iostream,但随后使用 stdio 中的 printf。
对 printf 的调用是错误的。它需要一个格式字符串。
Bison 显示了几个警告,如果您希望程序正常运行,您可能需要阅读这些警告并采取措施。
关于c++ - 包含由 flex 和 bison 生成的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27831253/