【问题标题】:Why does Flex/Lex reset variable of c++ code to its initial value?为什么 Flex/Lex 将 c++ 代码的变量重置为其初始值?
【发布时间】: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


【解决方案1】:

问题几乎可以肯定是您将namespace { ... } 放入头文件中。

包含此内容的每个 C++ 翻译单元都会获取头文件原始文本的副本,因此具有命名空间声明的副本。由于命名空间是匿名的,每个副本都是独立的;包含此的每个翻译单元都有自己的counter,以及dosomethingafterfinish

这非常类似于 C 语言中将一些静态定义放入标题中的情况,如下所示:

static int counter = 0;
static void dosomething(void) { printf("%d\n", ++counter); }
static void afterfinish(void) { printf("%d\n", counter); }

#include-s 此标头的每个 C 单元都有自己的计数器,以及对其进行操作的一对自己的私有函数 dosomethingafterfinish

词法分析器模块在自己的计数器上运行,而包含main 的模块中的afterfinish自己的计数器上运行,该计数器仍然为零。

如果您想要一个由您的模块共享的命名空间,只需给它一个名称。

// header file HelperCode.h
namespace parser_stuff {
  // We no longer *define* the counter in the header, just declare it.
  extern int counter;

  // And we use inline on functions defined in the header, otherwise
  // they will now be multiply defined!
  inline void dosomething()
  {
     counter++;
     // ... etc
  }

  // non-inline function
  void afterfinish();
}


// In one .cpp file somewhere, perhaps HelperCode.cpp
#include "HelperCode.h"

namespace parser_stuff {
  int counter = 0; // One program-wide definition of parser_stuff::counter.

  void afterfinish()
  {
    // ....
  }
}

当然,我们现在必须这样做

%{
    #include "HelperCode.h"     
    // ... etc
%}
%option c++
%option noyywrap
%option yylineno
%%

[\n]    { parser_stuff::dosomething();}

// ...etc
%%

否则:

%{
    #include "HelperCode.h"     
    // ... etc

    // one of these: bring in a specific identifier, or whole namespace:
    using parser_stuff::dosomething;
    using namespace parser_stuff;
%}
%option c++
%option noyywrap
%option yylineno
%%

[\n]    { dosomething();}

// ...etc
%%

在引用afterfinish的主模块中类似。

【讨论】:

  • 感谢您的有用回答,现在可以使用了。
猜你喜欢
  • 1970-01-01
  • 2021-02-18
  • 2019-09-03
  • 2017-01-22
  • 2011-01-06
  • 2021-12-31
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多