包括由 flex 和 bison 生成的代码

Include generated code by flex and bison

本文关键字:代码 bison flex 包括      更新时间:2023-10-16

我在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文件,我发现有定义的!

您有许多问题:

  1. Bison和Flex生成C代码,然后你需要编译这些代码并与你的程序链接。您的问题没有表明您已执行此操作。

  2. 如果您希望能够在 main.cpp 文件中使用 elementos 变量,则需要声明它。它可能在其他地方定义,但编译器在编译 main.cpp 时不知道这一点。在外部"C"部分内添加此行:extern int elementos;

  3. 您有两个不同的主要功能。

  4. 在main.cpp中,你 #include iostream,但随后使用stdio的printf。

  5. 对printf的调用是错误的。它需要一个格式字符串。

  6. Bison显示了几个警告,如果您希望程序正常工作,您可能需要阅读并执行一些操作。