【发布时间】:2015-12-23 22:30:52
【问题描述】:
我试图使用带有 C++ 的 Flex 和 Bison 创建简单的编译器,但我不明白为什么当 Flex 到达文件末尾时,它会将 C++ 文件中声明的变量重置为其初始值。
在 lex.l 文件中:
%{
#include "HelperCode.h"
// ... etc
%}
%option c++
%option noyywrap
%option yylineno
%%
[\n] { dosomething();}
// ...etc
%%
和 HelperCode.h 文件:
namespace
{
int counter = 0;
//rest of code
void dosomething()
{
counter++;
cout << counter << " ";
// here it will print the correct values based on input
// ex: 1 2 3 4 5
}
void afterfinish()
{
cout << endl << counter;
// but here it will print '0', like if the counter reset to 0
}
}
在 yacc.y 文件中:
// ... etc
// ...
void main(void)
{
Parser* p = new Parser();
p->parse();
afterfinish();
}
【问题讨论】:
-
flex 不这样做。你确定这不是你在做的事情吗?
-
计数器需要在类中,而不是命名空间中。
标签: c++ bison flex-lexer