g++ 编译器无法识别 lex 的内置 input() 函数

g++ compiler is not recognizing inbuilt input() function of lex

代码在 gcc 编译器上运行良好。但我需要使用 g++

error: ‘input’ was not declared in this scope
 while ((c = input()) != 0)  
                   ^

这个错误是在我用 yacclink 之后出现的

static void comment(void)
{
   int c;

   while ((c = input()) != 0)
    if (c == '*')
    {
        while ((c = input()) == '*')
            ;

        if (c == '/')
            return;

        if (c == 0)
            break;
    }
  yyerror("unterminated comment");
}

我认为这是由于混合了 C 和 C++。我已经有一段时间没有使用 lex 了,不记得你是否必须声明函数或者它们是由包含提供的,但你应该做的是将 input 的声明包装在 extern "C" {} 中块。

C 模式下的 Yacc 没有声明很多东西,你必须手动提供 input() 的声明。

(提示:尝试使用 bison/flex,我认为它们更好地支持使用 C++ 编译器进行编译)

添加:

extern "C" int input();

如果你打算用 C++ 编译 flex 生成的扫描器,那么你需要使用 yyinput 而不是 input。在scanner中,函数的名字取决于编译器是C还是C++,据说是为了避免名字冲突(虽然我不知道是哪个版本的C++定义了这个名字input):

#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif

此行为记录在 flex manual:

(Note that if the scanner is compiled using C++, then input() is instead referred to as yyinput(), in order to avoid a name clash with the C++ stream by the name of input.)