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

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

本文关键字:input 内置 函数 lex 编译器 识别 g++      更新时间:2023-10-16

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

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

与yacc链接后发生错误

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++编译flex生成的扫描器,那么您需要使用yyinput而不是input。在扫描器中,函数的名称取决于编译器是C还是c++,据称是为了避免名称冲突(尽管我不知道哪个版本的c++定义了名称input):

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

此行为在flex手册中有记录:

(注意,如果扫描器是使用c++编译的,那么input()将被称为yyinput(),以避免与名为input的c++流发生名称冲突。)

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

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

(提示:尝试bison/flex代替,我认为他们支持编译与c++编译器更好)

添加:

extern "C" int input();